CIRCT 24.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 is self-referential (its input is itself), we can't remove it.
393 if (wire.getInput() == wire.getResult())
394 return failure();
395
396 // If the wire has a name or an `sv.namehint` attribute, propagate it as an
397 // `sv.namehint` to the expression.
398 if (auto *inputOp = wire.getInput().getDefiningOp())
399 if (auto name = chooseName(wire, inputOp))
400 rewriter.modifyOpInPlace(inputOp,
401 [&] { inputOp->setAttr("sv.namehint", name); });
402
403 rewriter.replaceOp(wire, wire.getInput());
404 return success();
405}
406
407//===----------------------------------------------------------------------===//
408// AggregateConstantOp
409//===----------------------------------------------------------------------===//
410
411static LogicalResult checkAttributes(Operation *op, Attribute attr, Type type) {
412 // If this is a type alias, get the underlying type.
413 if (auto typeAlias = dyn_cast<TypeAliasType>(type))
414 type = typeAlias.getCanonicalType();
415
416 if (auto structType = dyn_cast<StructType>(type)) {
417 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
418 if (!arrayAttr)
419 return op->emitOpError("expected array attribute for constant of type ")
420 << type;
421 if (structType.getElements().size() != arrayAttr.size())
422 return op->emitOpError("array attribute (")
423 << arrayAttr.size() << ") has wrong size for struct constant ("
424 << structType.getElements().size() << ")";
425
426 for (auto [attr, fieldInfo] :
427 llvm::zip(arrayAttr.getValue(), structType.getElements())) {
428 if (failed(checkAttributes(op, attr, fieldInfo.type)))
429 return failure();
430 }
431 } else if (auto arrayType = dyn_cast<ArrayType>(type)) {
432 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
433 if (!arrayAttr)
434 return op->emitOpError("expected array attribute for constant of type ")
435 << type;
436 if (arrayType.getNumElements() != arrayAttr.size())
437 return op->emitOpError("array attribute (")
438 << arrayAttr.size() << ") has wrong size for array constant ("
439 << arrayType.getNumElements() << ")";
440
441 auto elementType = arrayType.getElementType();
442 for (auto attr : arrayAttr.getValue()) {
443 if (failed(checkAttributes(op, attr, elementType)))
444 return failure();
445 }
446 } else if (auto arrayType = dyn_cast<UnpackedArrayType>(type)) {
447 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
448 if (!arrayAttr)
449 return op->emitOpError("expected array attribute for constant of type ")
450 << type;
451 auto elementType = arrayType.getElementType();
452 if (arrayType.getNumElements() != arrayAttr.size())
453 return op->emitOpError("array attribute (")
454 << arrayAttr.size()
455 << ") has wrong size for unpacked array constant ("
456 << arrayType.getNumElements() << ")";
457
458 for (auto attr : arrayAttr.getValue()) {
459 if (failed(checkAttributes(op, attr, elementType)))
460 return failure();
461 }
462 } else if (auto enumType = dyn_cast<EnumType>(type)) {
463 auto stringAttr = dyn_cast<StringAttr>(attr);
464 if (!stringAttr)
465 return op->emitOpError("expected string attribute for constant of type ")
466 << type;
467 } else if (auto intType = dyn_cast<IntegerType>(type)) {
468 // Check the attribute kind is correct.
469 auto intAttr = dyn_cast<IntegerAttr>(attr);
470 if (!intAttr)
471 return op->emitOpError("expected integer attribute for constant of type ")
472 << type;
473 // Check the bitwidth is correct.
474 if (intAttr.getValue().getBitWidth() != intType.getWidth())
475 return op->emitOpError("hw.constant attribute bitwidth "
476 "doesn't match return type");
477 } else if (auto typedAttr = dyn_cast<TypedAttr>(attr)) {
478 if (typedAttr.getType() != type)
479 return op->emitOpError("typed attr doesn't match the return type ")
480 << type;
481 } else {
482 return op->emitOpError("unknown element type ") << type;
483 }
484 return success();
485}
486
487LogicalResult AggregateConstantOp::verify() {
488 return checkAttributes(*this, getFieldsAttr(), getType());
489}
490
491OpFoldResult AggregateConstantOp::fold(FoldAdaptor) { return getFieldsAttr(); }
492
493//===----------------------------------------------------------------------===//
494// ParamValueOp
495//===----------------------------------------------------------------------===//
496
497static ParseResult parseParamValue(OpAsmParser &p, Attribute &value,
498 Type &resultType) {
499 if (p.parseType(resultType) || p.parseEqual() ||
500 p.parseAttribute(value, resultType))
501 return failure();
502 return success();
503}
504
505static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value,
506 Type resultType) {
507 p << resultType << " = ";
508 p.printAttributeWithoutType(value);
509}
510
511LogicalResult ParamValueOp::verify() {
512 // Check that the attribute expression is valid in this module.
514 getValue(), (*this)->getParentOfType<hw::HWModuleOp>(), *this);
515}
516
517OpFoldResult ParamValueOp::fold(FoldAdaptor adaptor) {
518 assert(adaptor.getOperands().empty() && "hw.param.value has no operands");
519 return getValueAttr();
520}
521
522//===----------------------------------------------------------------------===//
523// HWModuleOp
524//===----------------------------------------------------------------------===/
525
526/// Return true if isAnyModule or instance.
527bool hw::isAnyModuleOrInstance(Operation *moduleOrInstance) {
528 return isa<HWModuleLike, InstanceOp>(moduleOrInstance);
529}
530
531/// Return the signature for a module as a function type from the module itself
532/// or from an hw::InstanceOp.
533FunctionType hw::getModuleType(Operation *moduleOrInstance) {
534 return TypeSwitch<Operation *, FunctionType>(moduleOrInstance)
535 .Case<InstanceOp>([](auto instance) {
536 SmallVector<Type> inputs(instance->getOperandTypes());
537 SmallVector<Type> results(instance->getResultTypes());
538 return FunctionType::get(instance->getContext(), inputs, results);
539 })
540 .Case<HWModuleLike>(
541 [](auto mod) { return mod.getHWModuleType().getFuncType(); })
542 .Default([](Operation *op) {
543 return cast<FunctionType>(
544 cast<mlir::FunctionOpInterface>(op).getFunctionType());
545 });
546}
547
548/// Return the name to use for the Verilog module that we're referencing
549/// here. This is typically the symbol, but can be overridden with the
550/// verilogName attribute.
551StringAttr hw::getVerilogModuleNameAttr(Operation *module) {
552 auto nameAttr = module->getAttrOfType<StringAttr>("verilogName");
553 if (nameAttr)
554 return nameAttr;
555
556 if (auto symbol = dyn_cast<mlir::SymbolOpInterface>(module))
557 return symbol.getNameAttr();
558 return {};
559}
560
561template <typename ModuleTy>
562static void
563buildModule(OpBuilder &builder, OperationState &result, StringAttr name,
564 const ModulePortInfo &ports, ArrayAttr parameters,
565 ArrayRef<NamedAttribute> attributes, StringAttr comment) {
566 using namespace mlir::function_interface_impl;
567
568 // Add an attribute for the name.
569 result.addAttribute(ModuleTy::getSymNameAttrName(result.name), name);
570
571 SmallVector<Attribute> perPortAttrs;
572 SmallVector<ModulePort> portTypes;
573
574 for (auto elt : ports) {
575 portTypes.push_back(elt);
576 llvm::SmallVector<NamedAttribute> portAttrs;
577 if (elt.attrs)
578 llvm::copy(elt.attrs, std::back_inserter(portAttrs));
579 perPortAttrs.push_back(builder.getDictionaryAttr(portAttrs));
580 }
581
582 // Allow clients to pass in null for the parameters list.
583 if (!parameters)
584 parameters = builder.getArrayAttr({});
585
586 // Record the argument and result types as an attribute.
587 auto type = ModuleType::get(builder.getContext(), portTypes);
588 result.addAttribute(ModuleTy::getModuleTypeAttrName(result.name),
589 TypeAttr::get(type));
590 result.addAttribute("per_port_attrs",
591 arrayOrEmpty(builder.getContext(), perPortAttrs));
592 result.addAttribute("parameters", parameters);
593 if (!comment)
594 comment = builder.getStringAttr("");
595 result.addAttribute("comment", comment);
596 result.addAttributes(attributes);
597 result.addRegion();
598}
599
600/// Internal implementation of argument/result insertion and removal on modules.
602 MLIRContext *context, ArrayRef<std::pair<unsigned, PortInfo>> insertArgs,
603 ArrayRef<unsigned> removeArgs, ArrayRef<Attribute> oldArgNames,
604 ArrayRef<Type> oldArgTypes, ArrayRef<Attribute> oldArgAttrs,
605 ArrayRef<Location> oldArgLocs, SmallVector<Attribute> &newArgNames,
606 SmallVector<Type> &newArgTypes, SmallVector<Attribute> &newArgAttrs,
607 SmallVector<Location> &newArgLocs, Block *body = nullptr) {
608
609#ifndef NDEBUG
610 // Check that the `insertArgs` and `removeArgs` indices are in ascending
611 // order.
612 assert(llvm::is_sorted(insertArgs,
613 [](auto &a, auto &b) { return a.first < b.first; }) &&
614 "insertArgs must be in ascending order");
615 assert(llvm::is_sorted(removeArgs, [](auto &a, auto &b) { return a < b; }) &&
616 "removeArgs must be in ascending order");
617#endif
618
619 auto oldArgCount = oldArgTypes.size();
620 auto newArgCount = oldArgCount + insertArgs.size() - removeArgs.size();
621 assert((int)newArgCount >= 0);
622
623 newArgNames.reserve(newArgCount);
624 newArgTypes.reserve(newArgCount);
625 newArgAttrs.reserve(newArgCount);
626 newArgLocs.reserve(newArgCount);
627
628 auto emptyDictAttr = DictionaryAttr::get(context, {});
629 auto unknownLoc = UnknownLoc::get(context);
630
631 BitVector erasedIndices;
632 if (body)
633 erasedIndices.resize(oldArgCount + insertArgs.size());
634
635 for (unsigned argIdx = 0, idx = 0; argIdx <= oldArgCount; ++argIdx, ++idx) {
636 // Insert new ports at this position.
637 while (!insertArgs.empty() && insertArgs[0].first == argIdx) {
638 auto port = insertArgs[0].second;
639 if (port.dir == ModulePort::Direction::InOut &&
640 !isa<InOutType>(port.type))
641 port.type = InOutType::get(port.type);
642 newArgNames.push_back(port.name);
643 newArgTypes.push_back(port.type);
644 newArgAttrs.push_back(port.attrs ? port.attrs : emptyDictAttr);
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 getSymNameAttr();
815}
816
817StringAttr HWModuleGeneratedOp::getVerilogModuleNameAttr() {
818 if (auto vName = getVerilogNameAttr()) {
819 return vName;
820 }
821 return getSymNameAttr();
822}
823
824void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
825 StringAttr name, const ModulePortInfo &ports,
826 StringRef verilogName, ArrayAttr parameters,
827 ArrayRef<NamedAttribute> attributes) {
828 buildModule<HWModuleExternOp>(builder, result, name, ports, parameters,
829 attributes, {});
830
831 // Add the port locations.
832 LocationAttr unknownLoc = builder.getUnknownLoc();
833 SmallVector<Attribute> portLocs;
834 for (auto elt : ports)
835 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
836 result.addAttribute("port_locs", builder.getArrayAttr(portLocs));
837
838 if (!verilogName.empty())
839 result.addAttribute("verilogName", builder.getStringAttr(verilogName));
840}
841
842void HWModuleExternOp::build(OpBuilder &builder, OperationState &result,
843 StringAttr name, ArrayRef<PortInfo> ports,
844 StringRef verilogName, ArrayAttr parameters,
845 ArrayRef<NamedAttribute> attributes) {
846 build(builder, result, name, ModulePortInfo(ports), verilogName, parameters,
847 attributes);
848}
849
850void HWModuleExternOp::modifyPorts(
851 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
852 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
853 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
854 modifyModulePorts(*this, insertInputs, insertOutputs, eraseInputs,
855 eraseOutputs);
856}
857
858void HWModuleExternOp::appendOutputs(
859 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
860
861void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
862 FlatSymbolRefAttr genKind, StringAttr name,
863 const ModulePortInfo &ports,
864 StringRef verilogName, ArrayAttr parameters,
865 ArrayRef<NamedAttribute> attributes) {
866 buildModule<HWModuleGeneratedOp>(builder, result, name, ports, parameters,
867 attributes, {});
868 // Add the port locations.
869 LocationAttr unknownLoc = builder.getUnknownLoc();
870 SmallVector<Attribute> portLocs;
871 for (auto elt : ports)
872 portLocs.push_back(elt.loc ? elt.loc : unknownLoc);
873 result.addAttribute("port_locs", builder.getArrayAttr(portLocs));
874
875 result.addAttribute("generatorKind", genKind);
876 if (!verilogName.empty())
877 result.addAttribute("verilogName", builder.getStringAttr(verilogName));
878}
879
880void HWModuleGeneratedOp::build(OpBuilder &builder, OperationState &result,
881 FlatSymbolRefAttr genKind, StringAttr name,
882 ArrayRef<PortInfo> ports, StringRef verilogName,
883 ArrayAttr parameters,
884 ArrayRef<NamedAttribute> attributes) {
885 build(builder, result, genKind, name, ModulePortInfo(ports), verilogName,
886 parameters, attributes);
887}
888
889void HWModuleGeneratedOp::modifyPorts(
890 ArrayRef<std::pair<unsigned, PortInfo>> insertInputs,
891 ArrayRef<std::pair<unsigned, PortInfo>> insertOutputs,
892 ArrayRef<unsigned> eraseInputs, ArrayRef<unsigned> eraseOutputs) {
893 modifyModulePorts(*this, insertInputs, insertOutputs, eraseInputs,
894 eraseOutputs);
895}
896
897void HWModuleGeneratedOp::appendOutputs(
898 ArrayRef<std::pair<StringAttr, Value>> outputs) {}
899
900static bool hasAttribute(StringRef name, ArrayRef<NamedAttribute> attrs) {
901 for (auto &argAttr : attrs)
902 if (argAttr.getName() == name)
903 return true;
904 return false;
905}
906
907template <typename ModuleTy>
908static ParseResult parseHWModuleOp(OpAsmParser &parser,
909 OperationState &result) {
910
911 using namespace mlir::function_interface_impl;
912 auto builder = parser.getBuilder();
913 auto loc = parser.getCurrentLocation();
914
915 // Parse the visibility attribute.
916 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
917
918 // Parse the name as a symbol.
919 StringAttr nameAttr;
920 if (parser.parseSymbolName(nameAttr,
921 ModuleTy::getSymNameAttrName(result.name),
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 =
1035 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
1036 if (auto visibility = mod.getOperation()->template getAttrOfType<StringAttr>(
1037 visibilityAttrName))
1038 p << visibility.getValue() << ' ';
1039
1040 // Print the operation and the function name.
1041 p.printSymbolName(mod.getName());
1042 if (auto gen = dyn_cast<HWModuleGeneratedOp>(mod.getOperation())) {
1043 p << ", ";
1044 p.printSymbolName(gen.getGeneratorKind());
1045 }
1046
1047 // Print the parameter list if present.
1048 printOptionalParameterList(p, mod.getOperation(), mod.getParameters());
1049
1051
1052 SmallVector<StringRef, 3> omittedAttrs;
1053 omittedAttrs.push_back(mod.getSymNameAttrName());
1054 if (isa<HWModuleGeneratedOp>(mod.getOperation()))
1055 omittedAttrs.push_back("generatorKind");
1056 if constexpr (std::is_same_v<ModuleTy, HWModuleOp>)
1057 omittedAttrs.push_back(mod.getResultLocsAttrName());
1058 else
1059 omittedAttrs.push_back(mod.getPortLocsAttrName());
1060 omittedAttrs.push_back(mod.getModuleTypeAttrName());
1061 omittedAttrs.push_back(mod.getPerPortAttrsAttrName());
1062 omittedAttrs.push_back(mod.getParametersAttrName());
1063 omittedAttrs.push_back(visibilityAttrName);
1064 if (auto cmt =
1065 mod.getOperation()->template getAttrOfType<StringAttr>("comment"))
1066 if (cmt.getValue().empty())
1067 omittedAttrs.push_back("comment");
1068
1069 mlir::function_interface_impl::printFunctionAttributes(p, mod.getOperation(),
1070 omittedAttrs);
1071}
1072
1073void HWModuleExternOp::print(OpAsmPrinter &p) { printModuleOp(p, *this); }
1074void HWModuleGeneratedOp::print(OpAsmPrinter &p) { printModuleOp(p, *this); }
1075
1076void HWModuleOp::print(OpAsmPrinter &p) {
1077 printModuleOp(p, *this);
1078
1079 // Print the body if this is not an external function.
1080 Region &body = getBody();
1081 if (!body.empty()) {
1082 p << " ";
1083 p.printRegion(body, /*printEntryBlockArgs=*/false,
1084 /*printBlockTerminators=*/true);
1085 }
1086}
1087
1088static LogicalResult verifyModuleCommon(HWModuleLike module) {
1089 assert(isa<HWModuleLike>(module) &&
1090 "verifier hook should only be called on modules");
1091
1092 if (auto portLocs = module->getAttrOfType<ArrayAttr>("port_locs"))
1093 if (!portLocs.empty() && portLocs.size() != module.getNumPorts())
1094 return module->emitOpError("requires ")
1095 << module.getNumPorts() << " port locations but got "
1096 << portLocs.size();
1097
1098 for (auto port : module.getPortList()) {
1099 auto result = success();
1100 port.type.walk([&](Type type) {
1101 if (failed(result))
1102 return;
1103 auto &dialect = type.getDialect();
1104 auto *interface =
1105 dialect.getRegisteredInterface<hw::HWModulePortTypeInterface>();
1106 if (!interface)
1107 return;
1108 result = interface->verifyHWModulePortType(
1109 [&] { return module->emitOpError(); }, port.dir, type);
1110 });
1111 if (failed(result))
1112 return result;
1113 }
1114
1115 SmallPtrSet<Attribute, 4> paramNames;
1116
1117 // Check parameter default values are sensible.
1118 for (auto param : module->getAttrOfType<ArrayAttr>("parameters")) {
1119 auto paramAttr = cast<ParamDeclAttr>(param);
1120
1121 // Check that we don't have any redundant parameter names. These are
1122 // resolved by string name: reuse of the same name would cause ambiguities.
1123 if (!paramNames.insert(paramAttr.getName()).second)
1124 return module->emitOpError("parameter ")
1125 << paramAttr << " has the same name as a previous parameter";
1126
1127 // Default values are allowed to be missing, check them if present.
1128 auto value = paramAttr.getValue();
1129 if (!value)
1130 continue;
1131
1132 auto typedValue = dyn_cast<TypedAttr>(value);
1133 if (!typedValue)
1134 return module->emitOpError("parameter ")
1135 << paramAttr << " should have a typed value; has value " << value;
1136
1137 if (typedValue.getType() != paramAttr.getType())
1138 return module->emitOpError("parameter ")
1139 << paramAttr << " should have type " << paramAttr.getType()
1140 << "; has type " << typedValue.getType();
1141
1142 // Verify that this is a valid parameter value, disallowing parameter
1143 // references. We could allow parameters to refer to each other in the
1144 // future with lexical ordering if there is a need.
1145 if (failed(checkParameterInContext(value, module, module,
1146 /*disallowParamRefs=*/true)))
1147 return failure();
1148 }
1149 return success();
1150}
1151
1152LogicalResult HWModuleOp::verify() {
1153 if (failed(verifyModuleCommon(*this)))
1154 return failure();
1155
1156 auto type = getModuleType();
1157 auto *body = getBodyBlock();
1158
1159 // Verify the number of block arguments.
1160 auto numInputs = type.getNumInputs();
1161 if (body->getNumArguments() != numInputs)
1162 return emitOpError("entry block must have ")
1163 << numInputs << " arguments to match module signature";
1164
1165 return success();
1166}
1167
1168LogicalResult HWModuleExternOp::verify() { return verifyModuleCommon(*this); }
1169
1170std::pair<StringAttr, BlockArgument>
1171HWModuleOp::insertInput(unsigned index, StringAttr name, Type ty) {
1172 // Find a unique name for the wire.
1173 Namespace ns;
1174 auto ports = getPortList();
1175 for (auto port : ports)
1176 ns.newName(port.name.getValue());
1177 auto nameAttr = StringAttr::get(getContext(), ns.newName(name.getValue()));
1178
1179 Block *body = getBodyBlock();
1180
1181 // Create a new port for the host clock.
1182 PortInfo port;
1183 port.name = nameAttr;
1185 port.type = ty;
1186 modifyModulePorts(getOperation(), {std::make_pair(index, port)}, {}, {}, {},
1187 body);
1188
1189 // Add a new argument.
1190 return {nameAttr, body->getArgument(index)};
1191}
1192
1193void HWModuleOp::insertOutputs(unsigned index,
1194 ArrayRef<std::pair<StringAttr, Value>> outputs) {
1195
1196 auto output = cast<OutputOp>(getBodyBlock()->getTerminator());
1197 assert(index <= output->getNumOperands() && "invalid output index");
1198
1199 // Rewrite the port list of the module.
1200 SmallVector<std::pair<unsigned, PortInfo>> indexedNewPorts;
1201 for (auto &[name, value] : outputs) {
1202 PortInfo port;
1203 port.name = name;
1205 port.type = value.getType();
1206 indexedNewPorts.emplace_back(index, port);
1207 }
1208 modifyModulePorts(getOperation(), {}, indexedNewPorts, {}, {},
1209 getBodyBlock());
1210
1211 // Rewrite the output op.
1212 for (auto &[name, value] : outputs)
1213 output->insertOperands(index++, value);
1214}
1215
1216void HWModuleOp::appendOutputs(ArrayRef<std::pair<StringAttr, Value>> outputs) {
1217 return insertOutputs(getNumOutputPorts(), outputs);
1218}
1219
1220void HWModuleOp::getAsmBlockArgumentNames(mlir::Region &region,
1221 mlir::OpAsmSetValueNameFn setNameFn) {
1222 getAsmBlockArgumentNamesImpl(region, setNameFn);
1223}
1224
1225void HWModuleExternOp::getAsmBlockArgumentNames(
1226 mlir::Region &region, mlir::OpAsmSetValueNameFn setNameFn) {
1227 getAsmBlockArgumentNamesImpl(region, setNameFn);
1228}
1229
1230template <typename ModTy>
1231static SmallVector<Location> getAllPortLocs(ModTy module) {
1232 auto locs = module.getPortLocs();
1233 if (locs) {
1234 SmallVector<Location> retval;
1235 retval.reserve(locs->size());
1236 for (auto l : *locs)
1237 retval.push_back(cast<Location>(l));
1238 // Either we have a length of 0 or the correct length
1239 assert(!locs->size() || locs->size() == module.getNumPorts());
1240 return retval;
1241 }
1242 return SmallVector<Location>(module.getNumPorts(),
1243 UnknownLoc::get(module.getContext()));
1244}
1245
1246SmallVector<Location> HWModuleOp::getAllPortLocs() {
1247 SmallVector<Location> portLocs;
1248 portLocs.reserve(getNumPorts());
1249 auto resultLocs = getResultLocsAttr();
1250 unsigned inputCount = 0;
1251 auto modType = getModuleType();
1252 auto unknownLoc = UnknownLoc::get(getContext());
1253 auto *body = getBodyBlock();
1254 for (unsigned i = 0, e = getNumPorts(); i < e; ++i) {
1255 if (modType.isOutput(i)) {
1256 auto loc = resultLocs
1257 ? cast<Location>(
1258 resultLocs.getValue()[portLocs.size() - inputCount])
1259 : unknownLoc;
1260 portLocs.push_back(loc);
1261 } else {
1262 auto loc = body ? body->getArgument(inputCount).getLoc() : unknownLoc;
1263 portLocs.push_back(loc);
1264 ++inputCount;
1265 }
1266 }
1267 return portLocs;
1268}
1269
1270SmallVector<Location> HWModuleExternOp::getAllPortLocs() {
1271 return ::getAllPortLocs(*this);
1272}
1273
1274SmallVector<Location> HWModuleGeneratedOp::getAllPortLocs() {
1275 return ::getAllPortLocs(*this);
1276}
1277
1278void HWModuleOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1279 SmallVector<Attribute> resultLocs;
1280 unsigned inputCount = 0;
1281 auto modType = getModuleType();
1282 auto *body = getBodyBlock();
1283 for (unsigned i = 0, e = getNumPorts(); i < e; ++i) {
1284 if (modType.isOutput(i))
1285 resultLocs.push_back(locs[i]);
1286 else
1287 body->getArgument(inputCount++).setLoc(cast<Location>(locs[i]));
1288 }
1289 setResultLocsAttr(ArrayAttr::get(getContext(), resultLocs));
1290}
1291
1292void HWModuleExternOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1293 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1294}
1295
1296void HWModuleGeneratedOp::setAllPortLocsAttrs(ArrayRef<Attribute> locs) {
1297 setPortLocsAttr(ArrayAttr::get(getContext(), locs));
1298}
1299
1300template <typename ModTy>
1301static void setAllPortNames(ArrayRef<Attribute> names, ModTy module) {
1302 auto numInputs = module.getNumInputPorts();
1303 SmallVector<Attribute> argNames(names.begin(), names.begin() + numInputs);
1304 SmallVector<Attribute> resNames(names.begin() + numInputs, names.end());
1305 auto oldType = module.getModuleType();
1306 SmallVector<ModulePort> newPorts(oldType.getPorts().begin(),
1307 oldType.getPorts().end());
1308 for (size_t i = 0UL, e = newPorts.size(); i != e; ++i)
1309 newPorts[i].name = cast<StringAttr>(names[i]);
1310 auto newType = ModuleType::get(module.getContext(), newPorts);
1311 module.setModuleType(newType);
1312}
1313
1314void HWModuleOp::setAllPortNames(ArrayRef<Attribute> names) {
1315 ::setAllPortNames(names, *this);
1316}
1317
1318void HWModuleExternOp::setAllPortNames(ArrayRef<Attribute> names) {
1319 ::setAllPortNames(names, *this);
1320}
1321
1322void HWModuleGeneratedOp::setAllPortNames(ArrayRef<Attribute> names) {
1323 ::setAllPortNames(names, *this);
1324}
1325
1326ArrayRef<Attribute> HWModuleOp::getAllPortAttrs() {
1327 auto attrs = getPerPortAttrs();
1328 if (attrs && !attrs->empty())
1329 return attrs->getValue();
1330 return {};
1331}
1332
1333ArrayRef<Attribute> HWModuleExternOp::getAllPortAttrs() {
1334 auto attrs = getPerPortAttrs();
1335 if (attrs && !attrs->empty())
1336 return attrs->getValue();
1337 return {};
1338}
1339
1340ArrayRef<Attribute> HWModuleGeneratedOp::getAllPortAttrs() {
1341 auto attrs = getPerPortAttrs();
1342 if (attrs && !attrs->empty())
1343 return attrs->getValue();
1344 return {};
1345}
1346
1347void HWModuleOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1348 setPerPortAttrsAttr(arrayOrEmpty(getContext(), attrs));
1349}
1350
1351void HWModuleExternOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1352 setPerPortAttrsAttr(arrayOrEmpty(getContext(), attrs));
1353}
1354
1355void HWModuleGeneratedOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
1356 setPerPortAttrsAttr(arrayOrEmpty(getContext(), attrs));
1357}
1358
1359void HWModuleOp::removeAllPortAttrs() {
1360 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1361}
1362
1363void HWModuleExternOp::removeAllPortAttrs() {
1364 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1365}
1366
1367void HWModuleGeneratedOp::removeAllPortAttrs() {
1368 setPerPortAttrsAttr(ArrayAttr::get(getContext(), {}));
1369}
1370
1371// This probably does really unexpected stuff when you change the number of
1372
1373template <typename ModTy>
1374static void setHWModuleType(ModTy &mod, ModuleType type) {
1375 auto argAttrs = mod.getAllInputAttrs();
1376 auto resAttrs = mod.getAllOutputAttrs();
1377 mod.setModuleTypeAttr(TypeAttr::get(type));
1378 unsigned newNumArgs = type.getNumInputs();
1379 unsigned newNumResults = type.getNumOutputs();
1380
1381 auto emptyDict = DictionaryAttr::get(mod.getContext());
1382 argAttrs.resize(newNumArgs, emptyDict);
1383 resAttrs.resize(newNumResults, emptyDict);
1384
1385 SmallVector<Attribute> attrs;
1386 attrs.append(argAttrs.begin(), argAttrs.end());
1387 attrs.append(resAttrs.begin(), resAttrs.end());
1388
1389 if (attrs.empty())
1390 return mod.removeAllPortAttrs();
1391 mod.setAllPortAttrs(attrs);
1392}
1393
1394void HWModuleOp::setHWModuleType(ModuleType type) {
1395 return ::setHWModuleType(*this, type);
1396}
1397
1398void HWModuleExternOp::setHWModuleType(ModuleType type) {
1399 return ::setHWModuleType(*this, type);
1400}
1401
1402void HWModuleGeneratedOp::setHWModuleType(ModuleType type) {
1403 return ::setHWModuleType(*this, type);
1404}
1405
1406/// Lookup the generator for the symbol. This returns null on
1407/// invalid IR.
1408Operation *HWModuleGeneratedOp::getGeneratorKindOp() {
1409 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
1410 return topLevelModuleOp.lookupSymbol(getGeneratorKind());
1411}
1412
1413LogicalResult
1414HWModuleGeneratedOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1415 auto *referencedKind =
1416 symbolTable.lookupNearestSymbolFrom(*this, getGeneratorKindAttr());
1417
1418 if (referencedKind == nullptr)
1419 return emitError("Cannot find generator definition '")
1420 << getGeneratorKind() << "'";
1421
1422 if (!isa<HWGeneratorSchemaOp>(referencedKind))
1423 return emitError("Symbol resolved to '")
1424 << referencedKind->getName()
1425 << "' which is not a HWGeneratorSchemaOp";
1426
1427 auto referencedKindOp = dyn_cast<HWGeneratorSchemaOp>(referencedKind);
1428 auto paramRef = referencedKindOp.getRequiredAttrs();
1429 auto dict = (*this)->getAttrDictionary();
1430 for (auto str : paramRef) {
1431 auto strAttr = dyn_cast<StringAttr>(str);
1432 if (!strAttr)
1433 return emitError("Unknown attribute type, expected a string");
1434 if (!dict.get(strAttr.getValue()))
1435 return emitError("Missing attribute '") << strAttr.getValue() << "'";
1436 }
1437
1438 return success();
1439}
1440
1441LogicalResult HWModuleGeneratedOp::verify() {
1442 return verifyModuleCommon(*this);
1443}
1444
1445void HWModuleGeneratedOp::getAsmBlockArgumentNames(
1446 mlir::Region &region, mlir::OpAsmSetValueNameFn setNameFn) {
1447 getAsmBlockArgumentNamesImpl(region, setNameFn);
1448}
1449
1450LogicalResult HWModuleOp::verifyBody() { return success(); }
1451
1452template <typename ModuleTy>
1453static SmallVector<PortInfo> getPortList(ModuleTy &mod) {
1454 auto modTy = mod.getHWModuleType();
1455 auto emptyDict = DictionaryAttr::get(mod.getContext());
1456 SmallVector<PortInfo> retval;
1457 auto locs = mod.getAllPortLocs();
1458 for (unsigned i = 0, e = modTy.getNumPorts(); i < e; ++i) {
1459 LocationAttr loc = locs[i];
1460 DictionaryAttr attrs =
1461 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(i));
1462 if (!attrs)
1463 attrs = emptyDict;
1464 retval.push_back({modTy.getPorts()[i],
1465 modTy.isOutput(i) ? modTy.getOutputIdForPortId(i)
1466 : modTy.getInputIdForPortId(i),
1467 attrs, loc});
1468 }
1469 return retval;
1470}
1471
1472template <typename ModuleTy>
1473static PortInfo getPort(ModuleTy &mod, size_t idx) {
1474 auto modTy = mod.getHWModuleType();
1475 auto emptyDict = DictionaryAttr::get(mod.getContext());
1476 LocationAttr loc = mod.getPortLoc(idx);
1477 DictionaryAttr attrs =
1478 dyn_cast_or_null<DictionaryAttr>(mod.getPortAttrs(idx));
1479 if (!attrs)
1480 attrs = emptyDict;
1481 return {modTy.getPorts()[idx],
1482 modTy.isOutput(idx) ? modTy.getOutputIdForPortId(idx)
1483 : modTy.getInputIdForPortId(idx),
1484 attrs, loc};
1485}
1486
1487//===----------------------------------------------------------------------===//
1488// InstanceOp
1489//===----------------------------------------------------------------------===//
1490
1491/// Create a instance that refers to a known module.
1492void InstanceOp::build(OpBuilder &builder, OperationState &result,
1493 Operation *module, StringAttr name,
1494 ArrayRef<Value> inputs, ArrayAttr parameters,
1495 InnerSymAttr innerSym) {
1496 if (!parameters)
1497 parameters = builder.getArrayAttr({});
1498
1499 auto mod = cast<hw::HWModuleLike>(module);
1500 auto argNames = builder.getArrayAttr(mod.getInputNames());
1501 auto resultNames = builder.getArrayAttr(mod.getOutputNames());
1502
1503 // Try to resolve the parameterized module type. If failed, use the module's
1504 // parmeterized type. If the client doesn't fix this error, the verifier will
1505 // fail.
1506 ModuleType modType = mod.getHWModuleType();
1507 FailureOr<ModuleType> resolvedModType = modType.resolveParametricTypes(
1508 parameters, result.location, /*emitErrors=*/false);
1509 if (succeeded(resolvedModType))
1510 modType = *resolvedModType;
1511 FunctionType funcType = resolvedModType->getFuncType();
1512 build(builder, result, funcType.getResults(), name,
1513 FlatSymbolRefAttr::get(SymbolTable::getSymbolName(module)), inputs,
1514 argNames, resultNames, parameters, innerSym, /*doNotPrint=*/{});
1515}
1516
1517std::optional<size_t> InstanceOp::getTargetResultIndex() {
1518 // Inner symbols on instance operations target the op not any result.
1519 return std::nullopt;
1520}
1521
1522LogicalResult InstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1524 *this, getModuleNameAttr(), getInputs(), getResultTypes(), getArgNames(),
1525 getResultNames(), getParameters(), symbolTable);
1526}
1527
1528LogicalResult InstanceOp::verify() {
1529 auto module = (*this)->getParentOfType<HWModuleOp>();
1530 if (!module)
1531 return success();
1532
1533 auto moduleParameters = module->getAttrOfType<ArrayAttr>("parameters");
1535 [&](const std::function<bool(InFlightDiagnostic &)> &fn) {
1536 auto diag = emitOpError();
1537 if (fn(diag))
1538 diag.attachNote(module->getLoc()) << "module declared here";
1539 };
1541 getParameters(), moduleParameters, emitError);
1542}
1543
1544ParseResult InstanceOp::parse(OpAsmParser &parser, OperationState &result) {
1545 StringAttr instanceNameAttr;
1546 InnerSymAttr innerSym;
1547 FlatSymbolRefAttr moduleNameAttr;
1548 SmallVector<OpAsmParser::UnresolvedOperand, 4> inputsOperands;
1549 SmallVector<Type, 1> inputsTypes, allResultTypes;
1550 ArrayAttr argNames, resultNames, parameters;
1551 auto noneType = parser.getBuilder().getType<NoneType>();
1552
1553 if (parser.parseAttribute(instanceNameAttr, noneType, "instanceName",
1554 result.attributes))
1555 return failure();
1556
1557 if (succeeded(parser.parseOptionalKeyword("sym"))) {
1558 // Parsing an optional symbol name doesn't fail, so no need to check the
1559 // result.
1560 if (parser.parseCustomAttributeWithFallback(innerSym))
1561 return failure();
1562 result.addAttribute(InnerSymbolTable::getInnerSymbolAttrName(), innerSym);
1563 }
1564
1565 llvm::SMLoc parametersLoc, inputsOperandsLoc;
1566 if (parser.parseAttribute(moduleNameAttr, noneType, "moduleName",
1567 result.attributes) ||
1568 parser.getCurrentLocation(&parametersLoc) ||
1569 parseOptionalParameterList(parser, parameters) ||
1570 parseInputPortList(parser, inputsOperands, inputsTypes, argNames) ||
1571 parser.resolveOperands(inputsOperands, inputsTypes, inputsOperandsLoc,
1572 result.operands) ||
1573 parser.parseArrow() ||
1574 parseOutputPortList(parser, allResultTypes, resultNames) ||
1575 parser.parseOptionalAttrDict(result.attributes)) {
1576 return failure();
1577 }
1578
1579 result.addAttribute("argNames", argNames);
1580 result.addAttribute("resultNames", resultNames);
1581 result.addAttribute("parameters", parameters);
1582 result.addTypes(allResultTypes);
1583 return success();
1584}
1585
1586void InstanceOp::print(OpAsmPrinter &p) {
1587 p << ' ';
1588 p.printAttributeWithoutType(getInstanceNameAttr());
1589 if (auto attr = getInnerSymAttr()) {
1590 p << " sym ";
1591 attr.print(p);
1592 }
1593 p << ' ';
1594 p.printAttributeWithoutType(getModuleNameAttr());
1595 printOptionalParameterList(p, *this, getParameters());
1596 printInputPortList(p, *this, getInputs(), getInputs().getTypes(),
1597 getArgNames());
1598 p << " -> ";
1599 printOutputPortList(p, *this, getResultTypes(), getResultNames());
1600
1601 p.printOptionalAttrDict(
1602 (*this)->getAttrs(),
1603 /*elidedAttrs=*/{"instanceName",
1604 InnerSymbolTable::getInnerSymbolAttrName(), "moduleName",
1605 "argNames", "resultNames", "parameters"});
1606}
1607
1608//===----------------------------------------------------------------------===//
1609// HWOutputOp
1610//===----------------------------------------------------------------------===//
1611
1612/// Verify that the num of operands and types fit the declared results.
1613LogicalResult OutputOp::verify() {
1614 // Check that the we (hw.output) have the same number of operands as our
1615 // region has results.
1616 ModuleType modType;
1617 if (auto mod = dyn_cast<HWModuleOp>((*this)->getParentOp()))
1618 modType = mod.getHWModuleType();
1619 else {
1620 emitOpError("must have a module parent");
1621 return failure();
1622 }
1623 auto modResults = modType.getOutputTypes();
1624 OperandRange outputValues = getOperands();
1625 if (modResults.size() != outputValues.size()) {
1626 emitOpError("must have same number of operands as region results.");
1627 return failure();
1628 }
1629
1630 // Check that the types of our operands and the region's results match.
1631 for (size_t i = 0, e = modResults.size(); i < e; ++i) {
1632 if (modResults[i] != outputValues[i].getType()) {
1633 emitOpError("output types must match module. In "
1634 "operand ")
1635 << i << ", expected " << modResults[i] << ", but got "
1636 << outputValues[i].getType() << ".";
1637 return failure();
1638 }
1639 }
1640
1641 return success();
1642}
1643
1644//===----------------------------------------------------------------------===//
1645// Other Operations
1646//===----------------------------------------------------------------------===//
1647
1648static ParseResult parseSliceTypes(OpAsmParser &p, Type &srcType,
1649 Type &idxType) {
1650 Type type;
1651 if (p.parseType(type))
1652 return p.emitError(p.getCurrentLocation(), "Expected type");
1653 auto arrType = type_dyn_cast<ArrayType>(type);
1654 if (!arrType)
1655 return p.emitError(p.getCurrentLocation(), "Expected !hw.array type");
1656 srcType = type;
1657 unsigned idxWidth = llvm::Log2_64_Ceil(arrType.getNumElements());
1658 idxType = IntegerType::get(p.getBuilder().getContext(), idxWidth);
1659 return success();
1660}
1661
1662static void printSliceTypes(OpAsmPrinter &p, Operation *, Type srcType,
1663 Type idxType) {
1664 p.printType(srcType);
1665}
1666
1667ParseResult ArrayCreateOp::parse(OpAsmParser &parser, OperationState &result) {
1668 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
1669 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
1670 Type elemType;
1671
1672 if (parser.parseOperandList(operands) ||
1673 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
1674 parser.parseType(elemType))
1675 return failure();
1676
1677 if (operands.size() == 0)
1678 return parser.emitError(inputOperandsLoc,
1679 "Cannot construct an array of length 0");
1680
1681 // Check for optional result type: " -> <type>"
1682 Type resultType;
1683 if (parser.parseOptionalArrow().succeeded()) {
1684 if (parser.parseType(resultType))
1685 return failure();
1686 result.addTypes(resultType);
1687 } else {
1688 result.addTypes({ArrayType::get(elemType, operands.size())});
1689 }
1690
1691 for (auto operand : operands)
1692 if (parser.resolveOperand(operand, elemType, result.operands))
1693 return failure();
1694 return success();
1695}
1696
1697void ArrayCreateOp::print(OpAsmPrinter &p) {
1698 p << " ";
1699 p.printOperands(getInputs());
1700 p.printOptionalAttrDict((*this)->getAttrs());
1701 p << " : " << getInputs()[0].getType();
1702
1703 // Print optional result type if it's not the default constructed type
1704 Type expectedType =
1705 ArrayType::get(getInputs()[0].getType(), getInputs().size());
1706 if (getType() != expectedType)
1707 p << " -> " << getType();
1708}
1709
1710void ArrayCreateOp::build(OpBuilder &b, OperationState &state,
1711 ValueRange values) {
1712 assert(values.size() > 0 && "Cannot build array of zero elements");
1713 Type elemType = values[0].getType();
1714 assert(llvm::all_of(
1715 values,
1716 [elemType](Value v) -> bool { return v.getType() == elemType; }) &&
1717 "All values must have same type.");
1718 build(b, state, ArrayType::get(elemType, values.size()), values);
1719}
1720
1721LogicalResult ArrayCreateOp::verify() {
1722 unsigned returnSize = hw::type_cast<ArrayType>(getType()).getNumElements();
1723 if (getInputs().size() != returnSize)
1724 return failure();
1725 return success();
1726}
1727
1728OpFoldResult ArrayCreateOp::fold(FoldAdaptor adaptor) {
1729 if (llvm::any_of(adaptor.getInputs(), [](Attribute attr) {
1730 return !isa_and_nonnull<IntegerAttr>(attr);
1731 }))
1732 return {};
1733 return ArrayAttr::get(getContext(), adaptor.getInputs());
1734}
1735
1736// Check whether an integer value is an offset from a base.
1737bool hw::isOffset(Value base, Value index, uint64_t offset) {
1738 if (auto constBase = base.getDefiningOp<hw::ConstantOp>()) {
1739 if (auto constIndex = index.getDefiningOp<hw::ConstantOp>()) {
1740 // If both values are a constant, check if index == base + offset.
1741 // To account for overflow, the addition is performed with an extra bit
1742 // and the offset is asserted to fit in the bit width of the base.
1743 auto baseValue = constBase.getValue();
1744 auto indexValue = constIndex.getValue();
1745
1746 unsigned bits = baseValue.getBitWidth();
1747 assert(bits == indexValue.getBitWidth() && "mismatched widths");
1748
1749 if (bits < 64 && offset >= (1ull << bits))
1750 return false;
1751
1752 APInt baseExt = baseValue.zextOrTrunc(bits + 1);
1753 APInt indexExt = indexValue.zextOrTrunc(bits + 1);
1754 return baseExt + offset == indexExt;
1755 }
1756 }
1757 return false;
1758}
1759
1760// Canonicalize a create of consecutive elements to a slice.
1761static LogicalResult foldCreateToSlice(ArrayCreateOp op,
1762 PatternRewriter &rewriter) {
1763 // Do not canonicalize create of get into a slice.
1764 auto arrayTy = hw::type_cast<ArrayType>(op.getType());
1765 if (arrayTy.getNumElements() <= 1)
1766 return failure();
1767 auto elemTy = arrayTy.getElementType();
1768
1769 // Check if create arguments are consecutive elements of the same array.
1770 // Attempt to break a create of gets into a sequence of consecutive intervals.
1771 struct Chunk {
1772 Value input;
1773 Value index;
1774 size_t size;
1775 };
1776 SmallVector<Chunk> chunks;
1777 for (Value value : llvm::reverse(op.getInputs())) {
1778 auto get = value.getDefiningOp<ArrayGetOp>();
1779 if (!get)
1780 return failure();
1781
1782 Value input = get.getInput();
1783 Value index = get.getIndex();
1784 if (!chunks.empty()) {
1785 auto &c = *chunks.rbegin();
1786 if (c.input == get.getInput() && isOffset(c.index, index, c.size)) {
1787 c.size++;
1788 continue;
1789 }
1790 }
1791
1792 chunks.push_back(Chunk{input, index, 1});
1793 }
1794
1795 // If there is a single slice, eliminate the create.
1796 if (chunks.size() == 1) {
1797 auto &chunk = chunks[0];
1798 rewriter.replaceOp(op, rewriter.createOrFold<ArraySliceOp>(
1799 op.getLoc(), arrayTy, chunk.input, chunk.index));
1800 return success();
1801 }
1802
1803 // If the number of chunks is significantly less than the number of
1804 // elements, replace the create with a concat of the identified slices.
1805 if (chunks.size() * 2 < arrayTy.getNumElements()) {
1806 SmallVector<Value> slices;
1807 for (auto &chunk : llvm::reverse(chunks)) {
1808 auto sliceTy = ArrayType::get(elemTy, chunk.size);
1809 slices.push_back(rewriter.createOrFold<ArraySliceOp>(
1810 op.getLoc(), sliceTy, chunk.input, chunk.index));
1811 }
1812 rewriter.replaceOpWithNewOp<ArrayConcatOp>(op, arrayTy, slices);
1813 return success();
1814 }
1815
1816 return failure();
1817}
1818
1819LogicalResult ArrayCreateOp::canonicalize(ArrayCreateOp op,
1820 PatternRewriter &rewriter) {
1821 if (succeeded(foldCreateToSlice(op, rewriter)))
1822 return success();
1823 return failure();
1824}
1825
1826Value ArrayCreateOp::getUniformElement() {
1827 if (!getInputs().empty() && llvm::all_equal(getInputs()))
1828 return getInputs()[0];
1829 return {};
1830}
1831
1832static std::optional<uint64_t> getUIntFromValue(Value value) {
1833 auto idxOp = dyn_cast_or_null<ConstantOp>(value.getDefiningOp());
1834 if (!idxOp)
1835 return std::nullopt;
1836 APInt idxAttr = idxOp.getValue();
1837 if (idxAttr.getBitWidth() > 64)
1838 return std::nullopt;
1839 return idxAttr.getLimitedValue();
1840}
1841
1842LogicalResult ArraySliceOp::verify() {
1843 unsigned inputSize =
1844 type_cast<ArrayType>(getInput().getType()).getNumElements();
1845 if (llvm::Log2_64_Ceil(inputSize) !=
1846 getLowIndex().getType().getIntOrFloatBitWidth())
1847 return emitOpError(
1848 "ArraySlice: index width must match clog2 of array size");
1849 return success();
1850}
1851
1852OpFoldResult ArraySliceOp::fold(FoldAdaptor adaptor) {
1853 // If we are slicing the entire input, then return it.
1854 if (getType() == getInput().getType())
1855 return getInput();
1856 return {};
1857}
1858
1859LogicalResult ArraySliceOp::canonicalize(ArraySliceOp op,
1860 PatternRewriter &rewriter) {
1861 auto sliceTy = hw::type_cast<ArrayType>(op.getType());
1862 auto elemTy = sliceTy.getElementType();
1863 uint64_t sliceSize = sliceTy.getNumElements();
1864 if (sliceSize == 0)
1865 return failure();
1866
1867 if (sliceSize == 1) {
1868 // slice(a, n) -> create(a[n])
1869 auto get = ArrayGetOp::create(rewriter, op.getLoc(), op.getInput(),
1870 op.getLowIndex());
1871 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(),
1872 get.getResult());
1873 return success();
1874 }
1875
1876 auto offsetOpt = getUIntFromValue(op.getLowIndex());
1877 if (!offsetOpt)
1878 return failure();
1879
1880 auto *inputOp = op.getInput().getDefiningOp();
1881 if (auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
1882 // slice(slice(a, n), m) -> slice(a, n + m)
1883 if (inputSlice == op)
1884 return failure();
1885
1886 auto inputIndex = inputSlice.getLowIndex();
1887 auto inputOffsetOpt = getUIntFromValue(inputIndex);
1888 if (!inputOffsetOpt)
1889 return failure();
1890
1891 uint64_t offset = *offsetOpt + *inputOffsetOpt;
1892 auto lowIndex =
1893 ConstantOp::create(rewriter, op.getLoc(), inputIndex.getType(), offset);
1894 rewriter.replaceOpWithNewOp<ArraySliceOp>(op, op.getType(),
1895 inputSlice.getInput(), lowIndex);
1896 return success();
1897 }
1898
1899 if (auto inputCreate = dyn_cast_or_null<ArrayCreateOp>(inputOp)) {
1900 // slice(create(a0, a1, ..., an), m) -> create(am, ...)
1901 auto inputs = inputCreate.getInputs();
1902
1903 uint64_t begin = inputs.size() - *offsetOpt - sliceSize;
1904 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(),
1905 inputs.slice(begin, sliceSize));
1906 return success();
1907 }
1908
1909 if (auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
1910 // slice(concat(a1, a2, ...)) -> concat(a2, slice(a3, ..), ...)
1911 SmallVector<Value> chunks;
1912 uint64_t sliceStart = *offsetOpt;
1913 for (auto input : llvm::reverse(inputConcat.getInputs())) {
1914 // Check whether the input intersects with the slice.
1915 uint64_t inputSize =
1916 hw::type_cast<ArrayType>(input.getType()).getNumElements();
1917 if (inputSize == 0 || inputSize <= sliceStart) {
1918 sliceStart -= inputSize;
1919 continue;
1920 }
1921
1922 // Find the indices to slice from this input by intersection.
1923 uint64_t cutEnd = std::min(inputSize, sliceStart + sliceSize);
1924 uint64_t cutSize = cutEnd - sliceStart;
1925 assert(cutSize != 0 && "slice cannot be empty");
1926
1927 if (cutSize == inputSize) {
1928 // The whole input fits in the slice, add it.
1929 assert(sliceStart == 0 && "invalid cut size");
1930 chunks.push_back(input);
1931 } else {
1932 // Slice the required bits from the input.
1933 unsigned width = inputSize == 1 ? 1 : llvm::Log2_64_Ceil(inputSize);
1934 auto lowIndex = ConstantOp::create(
1935 rewriter, op.getLoc(), rewriter.getIntegerType(width), sliceStart);
1936 chunks.push_back(ArraySliceOp::create(
1937 rewriter, op.getLoc(), hw::ArrayType::get(elemTy, cutSize), input,
1938 lowIndex));
1939 }
1940
1941 sliceStart = 0;
1942 sliceSize -= cutSize;
1943 if (sliceSize == 0)
1944 break;
1945 }
1946
1947 assert(chunks.size() > 0 && "missing sliced items");
1948 if (chunks.size() == 1)
1949 rewriter.replaceOp(op, chunks[0]);
1950 else
1951 rewriter.replaceOpWithNewOp<ArrayConcatOp>(
1952 op, llvm::to_vector(llvm::reverse(chunks)));
1953 return success();
1954 }
1955 return failure();
1956}
1957
1958//===----------------------------------------------------------------------===//
1959// ArrayConcatOp
1960//===----------------------------------------------------------------------===//
1961
1962static ParseResult parseArrayConcatTypes(OpAsmParser &p,
1963 SmallVectorImpl<Type> &inputTypes,
1964 Type &resultType) {
1965 Type elemType;
1966 uint64_t resultSize = 0;
1967
1968 auto parseElement = [&]() -> ParseResult {
1969 Type ty;
1970 if (p.parseType(ty))
1971 return failure();
1972 auto arrTy = type_dyn_cast<ArrayType>(ty);
1973 if (!arrTy)
1974 return p.emitError(p.getCurrentLocation(), "Expected !hw.array type");
1975 if (elemType && elemType != arrTy.getElementType())
1976 return p.emitError(p.getCurrentLocation(), "Expected array element type ")
1977 << elemType;
1978
1979 elemType = arrTy.getElementType();
1980 inputTypes.push_back(ty);
1981 resultSize += arrTy.getNumElements();
1982 return success();
1983 };
1984
1985 if (p.parseCommaSeparatedList(parseElement))
1986 return failure();
1987
1988 resultType = ArrayType::get(elemType, resultSize);
1989 return success();
1990}
1991
1992static void printArrayConcatTypes(OpAsmPrinter &p, Operation *,
1993 TypeRange inputTypes, Type resultType) {
1994 llvm::interleaveComma(inputTypes, p, [&p](Type t) { p << t; });
1995}
1996
1997void ArrayConcatOp::build(OpBuilder &b, OperationState &state,
1998 ValueRange values) {
1999 assert(!values.empty() && "Cannot build array of zero elements");
2000 ArrayType arrayTy = cast<ArrayType>(values[0].getType());
2001 Type elemTy = arrayTy.getElementType();
2002 assert(llvm::all_of(values,
2003 [elemTy](Value v) -> bool {
2004 return isa<ArrayType>(v.getType()) &&
2005 cast<ArrayType>(v.getType()).getElementType() ==
2006 elemTy;
2007 }) &&
2008 "All values must be of ArrayType with the same element type.");
2009
2010 uint64_t resultSize = 0;
2011 for (Value val : values)
2012 resultSize += cast<ArrayType>(val.getType()).getNumElements();
2013 build(b, state, ArrayType::get(elemTy, resultSize), values);
2014}
2015
2016OpFoldResult ArrayConcatOp::fold(FoldAdaptor adaptor) {
2017 if (getInputs().size() == 1)
2018 return getInputs()[0];
2019
2020 auto inputs = adaptor.getInputs();
2021 SmallVector<Attribute> array;
2022 for (size_t i = 0, e = getNumOperands(); i < e; ++i) {
2023 if (!inputs[i])
2024 return {};
2025 llvm::copy(cast<ArrayAttr>(inputs[i]), std::back_inserter(array));
2026 }
2027 return ArrayAttr::get(getContext(), array);
2028}
2029
2030// Flatten a concatenation of array creates into a single create.
2031static bool flattenConcatOp(ArrayConcatOp op, PatternRewriter &rewriter) {
2032 for (auto input : op.getInputs())
2033 if (!input.getDefiningOp<ArrayCreateOp>())
2034 return false;
2035
2036 SmallVector<Value> items;
2037 for (auto input : op.getInputs()) {
2038 auto create = cast<ArrayCreateOp>(input.getDefiningOp());
2039 for (auto item : create.getInputs())
2040 items.push_back(item);
2041 }
2042
2043 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, items);
2044 return true;
2045}
2046
2047// Merge consecutive slice expressions in a concatenation.
2048static bool mergeConcatSlices(ArrayConcatOp op, PatternRewriter &rewriter) {
2049 struct Slice {
2050 Value input;
2051 Value index;
2052 size_t size;
2053 Value op;
2054 SmallVector<Location> locs;
2055 };
2056
2057 SmallVector<Value> items;
2058 std::optional<Slice> last;
2059 bool changed = false;
2060
2061 auto concatenate = [&] {
2062 // If there is only one op in the slice, place it to the items list.
2063 if (!last)
2064 return;
2065 if (last->op) {
2066 items.push_back(last->op);
2067 last.reset();
2068 return;
2069 }
2070
2071 // Otherwise, create a new slice of with the given size and place it.
2072 // In this case, the concat op is replaced, using the new argument.
2073 changed = true;
2074 auto loc = FusedLoc::get(op.getContext(), last->locs);
2075 auto origTy = hw::type_cast<ArrayType>(last->input.getType());
2076 auto arrayTy = ArrayType::get(origTy.getElementType(), last->size);
2077 items.push_back(rewriter.createOrFold<ArraySliceOp>(
2078 loc, arrayTy, last->input, last->index));
2079
2080 last.reset();
2081 };
2082
2083 auto append = [&](Value op, Value input, Value index, size_t size) {
2084 // If this slice is an extension of the previous one, extend the size
2085 // saved. In this case, a new slice of is created and the concatenation
2086 // operator is rewritten. Otherwise, flush the last slice.
2087 if (last) {
2088 if (last->input == input && isOffset(last->index, index, last->size)) {
2089 last->size += size;
2090 last->op = {};
2091 last->locs.push_back(op.getLoc());
2092 return;
2093 }
2094 concatenate();
2095 }
2096 last.emplace(Slice{input, index, size, op, {op.getLoc()}});
2097 };
2098
2099 for (auto item : llvm::reverse(op.getInputs())) {
2100 if (auto slice = item.getDefiningOp<ArraySliceOp>()) {
2101 auto size = hw::type_cast<ArrayType>(slice.getType()).getNumElements();
2102 append(item, slice.getInput(), slice.getLowIndex(), size);
2103 continue;
2104 }
2105
2106 if (auto create = item.getDefiningOp<ArrayCreateOp>()) {
2107 if (create.getInputs().size() == 1) {
2108 if (auto get = create.getInputs()[0].getDefiningOp<ArrayGetOp>()) {
2109 append(item, get.getInput(), get.getIndex(), 1);
2110 continue;
2111 }
2112 }
2113 }
2114
2115 concatenate();
2116 items.push_back(item);
2117 }
2118 concatenate();
2119
2120 if (!changed)
2121 return false;
2122
2123 if (items.size() == 1) {
2124 rewriter.replaceOp(op, items[0]);
2125 } else {
2126 std::reverse(items.begin(), items.end());
2127 rewriter.replaceOpWithNewOp<ArrayConcatOp>(op, items);
2128 }
2129 return true;
2130}
2131
2132LogicalResult ArrayConcatOp::canonicalize(ArrayConcatOp op,
2133 PatternRewriter &rewriter) {
2134 // concat(create(a1, ...), create(a3, ...), ...) -> create(a1, ..., a3, ...)
2135 if (flattenConcatOp(op, rewriter))
2136 return success();
2137
2138 // concat(slice(a, n, m), slice(a, n + m, p)) -> concat(slice(a, n, m + p))
2139 if (mergeConcatSlices(op, rewriter))
2140 return success();
2141
2142 return failure();
2143}
2144
2145//===----------------------------------------------------------------------===//
2146// EnumConstantOp
2147//===----------------------------------------------------------------------===//
2148
2149ParseResult EnumConstantOp::parse(OpAsmParser &parser, OperationState &result) {
2150 // Parse a Type instead of an EnumType since the type might be a type alias.
2151 // The validity of the canonical type is checked during construction of the
2152 // EnumFieldAttr.
2153 Type type;
2154 StringRef field;
2155
2156 auto loc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
2157 if (parser.parseKeyword(&field) || parser.parseColonType(type))
2158 return failure();
2159
2160 auto fieldAttr = EnumFieldAttr::get(
2161 loc, StringAttr::get(parser.getContext(), field), type);
2162
2163 if (!fieldAttr)
2164 return failure();
2165
2166 result.addAttribute("field", fieldAttr);
2167 result.addTypes(type);
2168
2169 return success();
2170}
2171
2172void EnumConstantOp::print(OpAsmPrinter &p) {
2173 p << " " << getField().getField().getValue() << " : "
2174 << getField().getType().getValue();
2175}
2176
2177void EnumConstantOp::getAsmResultNames(
2178 function_ref<void(Value, StringRef)> setNameFn) {
2179 setNameFn(getResult(), getField().getField().str());
2180}
2181
2182void EnumConstantOp::build(OpBuilder &builder, OperationState &odsState,
2183 EnumFieldAttr field) {
2184 return build(builder, odsState, field.getType().getValue(), field);
2185}
2186
2187OpFoldResult EnumConstantOp::fold(FoldAdaptor adaptor) {
2188 assert(adaptor.getOperands().empty() && "constant has no operands");
2189 return getFieldAttr();
2190}
2191
2192LogicalResult EnumConstantOp::verify() {
2193 auto fieldAttr = getFieldAttr();
2194 auto fieldType = fieldAttr.getType().getValue();
2195 // This check ensures that we are using the exact same type, without looking
2196 // through type aliases.
2197 if (fieldType != getType())
2198 emitOpError("return type ")
2199 << getType() << " does not match attribute type " << fieldAttr;
2200 return success();
2201}
2202
2203//===----------------------------------------------------------------------===//
2204// EnumCmpOp
2205//===----------------------------------------------------------------------===//
2206
2207LogicalResult EnumCmpOp::verify() {
2208 // Compare the canonical types.
2209 auto lhsType = type_cast<EnumType>(getLhs().getType());
2210 auto rhsType = type_cast<EnumType>(getRhs().getType());
2211 if (rhsType != lhsType)
2212 emitOpError("types do not match");
2213 return success();
2214}
2215
2216//===----------------------------------------------------------------------===//
2217// StructCreateOp
2218//===----------------------------------------------------------------------===//
2219
2220ParseResult StructCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2221 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2222 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
2223 Type declOrAliasType;
2224
2225 if (parser.parseLParen() || parser.parseOperandList(operands) ||
2226 parser.parseRParen() || parser.parseOptionalAttrDict(result.attributes) ||
2227 parser.parseColonType(declOrAliasType))
2228 return failure();
2229
2230 auto declType = type_dyn_cast<StructType>(declOrAliasType);
2231 if (!declType)
2232 return parser.emitError(parser.getNameLoc(),
2233 "expected !hw.struct type or alias");
2234
2235 llvm::SmallVector<Type, 4> structInnerTypes;
2236 declType.getInnerTypes(structInnerTypes);
2237 result.addTypes(declOrAliasType);
2238
2239 if (parser.resolveOperands(operands, structInnerTypes, inputOperandsLoc,
2240 result.operands))
2241 return failure();
2242 return success();
2243}
2244
2245void StructCreateOp::print(OpAsmPrinter &printer) {
2246 printer << " (";
2247 printer.printOperands(getInput());
2248 printer << ")";
2249 printer.printOptionalAttrDict((*this)->getAttrs());
2250 printer << " : " << getType();
2251}
2252
2253LogicalResult StructCreateOp::verify() {
2254 auto elements = hw::type_cast<StructType>(getType()).getElements();
2255
2256 if (elements.size() != getInput().size())
2257 return emitOpError("structure field count mismatch");
2258
2259 for (const auto &[field, value] : llvm::zip(elements, getInput()))
2260 if (field.type != value.getType())
2261 return emitOpError("structure field `")
2262 << field.name << "` type does not match";
2263
2264 return success();
2265}
2266
2267OpFoldResult StructCreateOp::fold(FoldAdaptor adaptor) {
2268 // struct_create(struct_explode(x)) => x
2269 if (!getInput().empty())
2270 if (auto explodeOp = getInput()[0].getDefiningOp<StructExplodeOp>();
2271 explodeOp && getInput() == explodeOp.getResults() &&
2272 getResult().getType() == explodeOp.getInput().getType())
2273 return explodeOp.getInput();
2274
2275 auto inputs = adaptor.getInput();
2276 if (llvm::any_of(inputs, [](Attribute attr) {
2277 return !isa_and_nonnull<IntegerAttr>(attr);
2278 }))
2279 return {};
2280 return ArrayAttr::get(getContext(), inputs);
2281}
2282
2283LogicalResult StructCreateOp::canonicalize(StructCreateOp op,
2284 PatternRewriter &rewriter) {
2285 // Fold away a struct_create whose inputs are struct_extract ops that
2286 // reconstruct the same struct in field order from a single source value.
2287 Value foldVal;
2288 for (auto [i, operand] : llvm::enumerate(op.getInput())) {
2289 auto extractOp = operand.getDefiningOp<StructExtractOp>();
2290 if (!extractOp || extractOp.getFieldIndex() != i ||
2291 extractOp.getInput().getType() != op.getType()) {
2292 foldVal = {};
2293 break;
2294 }
2295 if (i == 0) {
2296 foldVal = extractOp.getInput();
2297 } else if (extractOp.getInput() != foldVal) {
2298 foldVal = {};
2299 break;
2300 }
2301 }
2302 if (foldVal && foldVal != op.getResult()) {
2303 rewriter.replaceOp(op, foldVal);
2304 return success();
2305 }
2306 return failure();
2307}
2308
2309//===----------------------------------------------------------------------===//
2310// StructExplodeOp
2311//===----------------------------------------------------------------------===//
2312
2313ParseResult StructExplodeOp::parse(OpAsmParser &parser,
2314 OperationState &result) {
2315 OpAsmParser::UnresolvedOperand operand;
2316 Type declType;
2317
2318 if (parser.parseOperand(operand) ||
2319 parser.parseOptionalAttrDict(result.attributes) ||
2320 parser.parseColonType(declType))
2321 return failure();
2322 auto structType = type_dyn_cast<StructType>(declType);
2323 if (!structType)
2324 return parser.emitError(parser.getNameLoc(),
2325 "invalid kind of type specified");
2326
2327 llvm::SmallVector<Type, 4> structInnerTypes;
2328 structType.getInnerTypes(structInnerTypes);
2329 result.addTypes(structInnerTypes);
2330
2331 if (parser.resolveOperand(operand, declType, result.operands))
2332 return failure();
2333 return success();
2334}
2335
2336void StructExplodeOp::print(OpAsmPrinter &printer) {
2337 printer << " ";
2338 printer.printOperand(getInput());
2339 printer.printOptionalAttrDict((*this)->getAttrs());
2340 printer << " : " << getInput().getType();
2341}
2342
2343LogicalResult StructExplodeOp::fold(FoldAdaptor adaptor,
2344 SmallVectorImpl<OpFoldResult> &results) {
2345 auto input = adaptor.getInput();
2346 if (!input)
2347 return failure();
2348 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(results));
2349 return success();
2350}
2351
2352LogicalResult StructExplodeOp::canonicalize(StructExplodeOp op,
2353 PatternRewriter &rewriter) {
2354 auto *inputOp = op.getInput().getDefiningOp();
2355 auto elements = type_cast<StructType>(op.getInput().getType()).getElements();
2356 auto result = failure();
2357 auto opResults = op.getResults();
2358 for (uint32_t index = 0; index < elements.size(); index++) {
2359 if (auto foldResult = foldStructExtract(inputOp, index)) {
2360 rewriter.replaceAllUsesWith(opResults[index], foldResult);
2361 result = success();
2362 }
2363 }
2364 return result;
2365}
2366
2367void StructExplodeOp::getAsmResultNames(
2368 function_ref<void(Value, StringRef)> setNameFn) {
2369 auto structType = type_cast<StructType>(getInput().getType());
2370 for (auto [res, field] : llvm::zip(getResults(), structType.getElements()))
2371 setNameFn(res, field.name.str());
2372}
2373
2374void StructExplodeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2375 Value input) {
2376 StructType inputType = dyn_cast<StructType>(input.getType());
2377 assert(inputType);
2378 SmallVector<Type, 16> fieldTypes;
2379 for (auto field : inputType.getElements())
2380 fieldTypes.push_back(field.type);
2381 build(odsBuilder, odsState, fieldTypes, input);
2382}
2383
2384//===----------------------------------------------------------------------===//
2385// StructExtractOp
2386//===----------------------------------------------------------------------===//
2387
2388/// Ensure an aggregate op's field index is within the bounds of
2389/// the aggregate type and the accessed field is of 'elementType'.
2390template <typename AggregateOp, typename AggregateType>
2391static LogicalResult verifyAggregateFieldIndexAndType(AggregateOp &op,
2392 AggregateType aggType,
2393 Type elementType) {
2394 auto index = op.getFieldIndex();
2395 if (index >= aggType.getElements().size())
2396 return op.emitOpError() << "field index " << index
2397 << " exceeds element count of aggregate type";
2398
2400 getCanonicalType(aggType.getElements()[index].type))
2401 return op.emitOpError()
2402 << "type " << aggType.getElements()[index].type
2403 << " of accessed field in aggregate at index " << index
2404 << " does not match expected type " << elementType;
2405
2406 return success();
2407}
2408
2409LogicalResult StructExtractOp::verify() {
2410 return verifyAggregateFieldIndexAndType<StructExtractOp, StructType>(
2411 *this, getInput().getType(), getType());
2412}
2413
2414/// Use the same parser for both struct_extract and union_extract since the
2415/// syntax is identical.
2416template <typename AggregateType>
2417static ParseResult parseExtractOp(OpAsmParser &parser, OperationState &result) {
2418 OpAsmParser::UnresolvedOperand operand;
2419 StringAttr fieldName;
2420 Type declType;
2421
2422 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2423 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2424 parser.parseOptionalAttrDict(result.attributes) ||
2425 parser.parseColonType(declType))
2426 return failure();
2427 auto aggType = type_dyn_cast<AggregateType>(declType);
2428 if (!aggType)
2429 return parser.emitError(parser.getNameLoc(),
2430 "invalid kind of type specified");
2431
2432 auto fieldIndex = aggType.getFieldIndex(fieldName);
2433 if (!fieldIndex) {
2434 parser.emitError(parser.getNameLoc(), "field name '" +
2435 fieldName.getValue() +
2436 "' not found in aggregate type");
2437 return failure();
2438 }
2439
2440 auto indexAttr =
2441 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2442 result.addAttribute("fieldIndex", indexAttr);
2443 Type resultType = aggType.getElements()[*fieldIndex].type;
2444 result.addTypes(resultType);
2445
2446 if (parser.resolveOperand(operand, declType, result.operands))
2447 return failure();
2448 return success();
2449}
2450
2451/// Use the same printer for both struct_extract and union_extract since the
2452/// syntax is identical.
2453template <typename AggType>
2454static void printExtractOp(OpAsmPrinter &printer, AggType op) {
2455 printer << " ";
2456 printer.printOperand(op.getInput());
2457 printer << "[\"" << op.getFieldName() << "\"]";
2458 printer.printOptionalAttrDict(op->getAttrs(), {"fieldIndex"});
2459 printer << " : " << op.getInput().getType();
2460}
2461
2462ParseResult StructExtractOp::parse(OpAsmParser &parser,
2463 OperationState &result) {
2464 return parseExtractOp<StructType>(parser, result);
2465}
2466
2467void StructExtractOp::print(OpAsmPrinter &printer) {
2468 printExtractOp(printer, *this);
2469}
2470
2471void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2472 Value input, StructType::FieldInfo field) {
2473 auto fieldIndex =
2474 type_cast<StructType>(input.getType()).getFieldIndex(field.name);
2475 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2476 build(builder, odsState, field.type, input, *fieldIndex);
2477}
2478
2479void StructExtractOp::build(OpBuilder &builder, OperationState &odsState,
2480 Value input, StringAttr fieldName) {
2481 auto structType = type_cast<StructType>(input.getType());
2482 auto fieldIndex = structType.getFieldIndex(fieldName);
2483 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2484 auto resultType = structType.getElements()[*fieldIndex].type;
2485 build(builder, odsState, resultType, input, *fieldIndex);
2486}
2487
2488OpFoldResult StructExtractOp::fold(FoldAdaptor adaptor) {
2489 if (auto constOperand = adaptor.getInput()) {
2490 // Fold extract from aggregate constant
2491 auto operandAttr = llvm::cast<ArrayAttr>(constOperand);
2492 return operandAttr.getValue()[getFieldIndex()];
2493 }
2494
2495 if (auto foldResult =
2496 foldStructExtract(getInput().getDefiningOp(), getFieldIndex()))
2497 return foldResult;
2498 return {};
2499}
2500
2501LogicalResult StructExtractOp::canonicalize(StructExtractOp op,
2502 PatternRewriter &rewriter) {
2503 auto *inputOp = op.getInput().getDefiningOp();
2504
2505 // b = extract(inject(x["a"], v0)["b"]) => extract(x, "b")
2506 if (auto structInject = dyn_cast_or_null<StructInjectOp>(inputOp)) {
2507 if (structInject.getFieldIndex() != op.getFieldIndex()) {
2508 rewriter.replaceOpWithNewOp<StructExtractOp>(
2509 op, op.getType(), structInject.getInput(), op.getFieldIndexAttr());
2510 return success();
2511 }
2512 }
2513
2514 return failure();
2515}
2516
2517void StructExtractOp::getAsmResultNames(
2518 function_ref<void(Value, StringRef)> setNameFn) {
2519 setNameFn(getResult(), getFieldName());
2520}
2521
2522//===----------------------------------------------------------------------===//
2523// StructInjectOp
2524//===----------------------------------------------------------------------===//
2525
2526void StructInjectOp::build(OpBuilder &builder, OperationState &odsState,
2527 Value input, StringAttr fieldName, Value newValue) {
2528 auto structType = type_cast<StructType>(input.getType());
2529 auto fieldIndex = structType.getFieldIndex(fieldName);
2530 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2531 build(builder, odsState, input, *fieldIndex, newValue);
2532}
2533
2534LogicalResult StructInjectOp::verify() {
2535 return verifyAggregateFieldIndexAndType<StructInjectOp, StructType>(
2536 *this, getInput().getType(), getNewValue().getType());
2537}
2538
2539ParseResult StructInjectOp::parse(OpAsmParser &parser, OperationState &result) {
2540 llvm::SMLoc inputOperandsLoc = parser.getCurrentLocation();
2541 OpAsmParser::UnresolvedOperand operand, val;
2542 StringAttr fieldName;
2543 Type declType;
2544
2545 if (parser.parseOperand(operand) || parser.parseLSquare() ||
2546 parser.parseAttribute(fieldName) || parser.parseRSquare() ||
2547 parser.parseComma() || parser.parseOperand(val) ||
2548 parser.parseOptionalAttrDict(result.attributes) ||
2549 parser.parseColonType(declType))
2550 return failure();
2551 auto structType = type_dyn_cast<StructType>(declType);
2552 if (!structType)
2553 return parser.emitError(inputOperandsLoc, "invalid kind of type specified");
2554
2555 auto fieldIndex = structType.getFieldIndex(fieldName);
2556 if (!fieldIndex) {
2557 parser.emitError(parser.getNameLoc(), "field name '" +
2558 fieldName.getValue() +
2559 "' not found in aggregate type");
2560 return failure();
2561 }
2562
2563 auto indexAttr =
2564 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2565 result.addAttribute("fieldIndex", indexAttr);
2566 result.addTypes(declType);
2567
2568 Type resultType = structType.getElements()[*fieldIndex].type;
2569 if (parser.resolveOperands({operand, val}, {declType, resultType},
2570 inputOperandsLoc, result.operands))
2571 return failure();
2572 return success();
2573}
2574
2575void StructInjectOp::print(OpAsmPrinter &printer) {
2576 printer << " ";
2577 printer.printOperand(getInput());
2578 printer << "[\"" << getFieldName() << "\"], ";
2579 printer.printOperand(getNewValue());
2580 printer.printOptionalAttrDict((*this)->getAttrs(), {"fieldIndex"});
2581 printer << " : " << getInput().getType();
2582}
2583
2584OpFoldResult StructInjectOp::fold(FoldAdaptor adaptor) {
2585 auto input = adaptor.getInput();
2586 auto newValue = adaptor.getNewValue();
2587 if (!input || !newValue)
2588 return {};
2589 SmallVector<Attribute> array;
2590 llvm::copy(cast<ArrayAttr>(input), std::back_inserter(array));
2591 array[getFieldIndex()] = newValue;
2592 return ArrayAttr::get(getContext(), array);
2593}
2594
2595LogicalResult StructInjectOp::canonicalize(StructInjectOp op,
2596 PatternRewriter &rewriter) {
2597 // If this inject is only used as an input to another inject, don't try to
2598 // canonicalize it. It will be included in that other op's canonicalization
2599 // attempt. This avoids doing redundant work.
2600 if (op->hasOneUse()) {
2601 auto &use = *op->use_begin();
2602 if (isa<StructInjectOp>(use.getOwner()) && use.getOperandNumber() == 0)
2603 return failure();
2604 }
2605
2606 // Canonicalize multiple injects into a create op and eliminate overwrites.
2607 SmallPtrSet<Operation *, 4> injects;
2608 DenseMap<StringAttr, Value> fields;
2609
2610 // Chase a chain of injects. Bail out if cycles are present.
2611 StructInjectOp inject = op;
2612 Value input;
2613 do {
2614 if (!injects.insert(inject).second)
2615 break;
2616
2617 fields.try_emplace(inject.getFieldNameAttr(), inject.getNewValue());
2618 input = inject.getInput();
2619 inject = dyn_cast_or_null<StructInjectOp>(input.getDefiningOp());
2620 } while (inject);
2621 assert(input && "missing input to inject chain");
2622
2623 auto ty = hw::type_cast<StructType>(op.getType());
2624 auto elements = ty.getElements();
2625
2626 // If the inject chain sets all fields, canonicalize to create.
2627 if (fields.size() == elements.size()) {
2628 SmallVector<Value> createFields;
2629 for (const auto &field : elements) {
2630 auto it = fields.find(field.name);
2631 assert(it != fields.end() && "missing field");
2632 createFields.push_back(it->second);
2633 }
2634 rewriter.replaceOpWithNewOp<StructCreateOp>(op, ty, createFields);
2635 return success();
2636 }
2637
2638 // Nothing to canonicalize, only the original inject in the chain.
2639 if (injects.size() == fields.size())
2640 return failure();
2641
2642 // Eliminate overwrites. The hash map contains the last write to each field.
2643 for (uint32_t fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
2644 auto it = fields.find(elements[fieldIndex].name);
2645 if (it == fields.end())
2646 continue;
2647 input = StructInjectOp::create(rewriter, op.getLoc(), ty, input, fieldIndex,
2648 it->second);
2649 }
2650
2651 rewriter.replaceOp(op, input);
2652 return success();
2653}
2654
2655//===----------------------------------------------------------------------===//
2656// UnionCreateOp
2657//===----------------------------------------------------------------------===//
2658
2659LogicalResult UnionCreateOp::verify() {
2660 return verifyAggregateFieldIndexAndType<UnionCreateOp, UnionType>(
2661 *this, getType(), getInput().getType());
2662}
2663
2664void UnionCreateOp::build(OpBuilder &builder, OperationState &odsState,
2665 Type unionType, StringAttr fieldName, Value input) {
2666 auto fieldIndex = type_cast<UnionType>(unionType).getFieldIndex(fieldName);
2667 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2668 build(builder, odsState, unionType, *fieldIndex, input);
2669}
2670
2671ParseResult UnionCreateOp::parse(OpAsmParser &parser, OperationState &result) {
2672 Type declOrAliasType;
2673 StringAttr fieldName;
2674 OpAsmParser::UnresolvedOperand input;
2675 llvm::SMLoc fieldLoc = parser.getCurrentLocation();
2676
2677 if (parser.parseAttribute(fieldName) || parser.parseComma() ||
2678 parser.parseOperand(input) ||
2679 parser.parseOptionalAttrDict(result.attributes) ||
2680 parser.parseColonType(declOrAliasType))
2681 return failure();
2682
2683 auto declType = type_dyn_cast<UnionType>(declOrAliasType);
2684 if (!declType)
2685 return parser.emitError(parser.getNameLoc(),
2686 "expected !hw.union type or alias");
2687
2688 auto fieldIndex = declType.getFieldIndex(fieldName);
2689 if (!fieldIndex) {
2690 parser.emitError(fieldLoc, "cannot find union field '")
2691 << fieldName.getValue() << '\'';
2692 return failure();
2693 }
2694
2695 auto indexAttr =
2696 IntegerAttr::get(IntegerType::get(parser.getContext(), 32), *fieldIndex);
2697 result.addAttribute("fieldIndex", indexAttr);
2698 Type inputType = declType.getElements()[*fieldIndex].type;
2699
2700 if (parser.resolveOperand(input, inputType, result.operands))
2701 return failure();
2702 result.addTypes({declOrAliasType});
2703 return success();
2704}
2705
2706void UnionCreateOp::print(OpAsmPrinter &printer) {
2707 printer << " \"" << getFieldName() << "\", ";
2708 printer.printOperand(getInput());
2709 printer.printOptionalAttrDict((*this)->getAttrs(), {"fieldIndex"});
2710 printer << " : " << getType();
2711}
2712
2713//===----------------------------------------------------------------------===//
2714// UnionExtractOp
2715//===----------------------------------------------------------------------===//
2716
2717ParseResult UnionExtractOp::parse(OpAsmParser &parser, OperationState &result) {
2718 return parseExtractOp<UnionType>(parser, result);
2719}
2720
2721void UnionExtractOp::print(OpAsmPrinter &printer) {
2722 printExtractOp(printer, *this);
2723}
2724
2725LogicalResult UnionExtractOp::inferReturnTypes(
2726 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
2727 DictionaryAttr attrs, mlir::PropertyRef properties,
2728 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
2729 Adaptor adaptor(operands, attrs, properties, regions);
2730 auto unionElements =
2731 hw::type_cast<UnionType>((adaptor.getInput().getType())).getElements();
2732 unsigned fieldIndex = adaptor.getFieldIndexAttr().getValue().getZExtValue();
2733 if (fieldIndex >= unionElements.size()) {
2734 if (loc)
2735 mlir::emitError(*loc, "field index " + Twine(fieldIndex) +
2736 " exceeds element count of aggregate type");
2737 return failure();
2738 }
2739 results.push_back(unionElements[fieldIndex].type);
2740 return success();
2741}
2742
2743void UnionExtractOp::build(OpBuilder &odsBuilder, OperationState &odsState,
2744 Value input, StringAttr fieldName) {
2745 auto unionType = type_cast<UnionType>(input.getType());
2746 auto fieldIndex = unionType.getFieldIndex(fieldName);
2747 assert(fieldIndex.has_value() && "field name not found in aggregate type");
2748 auto resultType = unionType.getElements()[*fieldIndex].type;
2749 build(odsBuilder, odsState, resultType, input, *fieldIndex);
2750}
2751
2752LogicalResult UnionExtractOp::canonicalize(UnionExtractOp extractOp,
2753 PatternRewriter &rewriter) {
2754 // hw.union_extract("F1", hw.union_create("F2", a)) -> a, if F1 and F2 map to
2755 // the same bits
2756 if (auto createOp = extractOp.getInput().getDefiningOp<UnionCreateOp>()) {
2757 if (createOp.getInput().getType() == extractOp.getType() &&
2758 createOp.getInput() != extractOp.getResult()) {
2759 auto unionTypeElts =
2760 cast<UnionType>(extractOp.getInput().getType()).getElements();
2761 if (unionTypeElts[createOp.getFieldIndex()].offset ==
2762 unionTypeElts[extractOp.getFieldIndex()].offset) {
2763 rewriter.replaceOp(extractOp, createOp.getInput());
2764 return success();
2765 }
2766 }
2767 }
2768 // Forward bitcasts if the extract covers the entire union
2769 if (auto bitcastOp = extractOp.getInput().getDefiningOp<BitcastOp>()) {
2770 auto inputWidth = getBitWidth(bitcastOp.getInput().getType());
2771 assert(inputWidth >= 0 &&
2772 inputWidth == getBitWidth(extractOp.getInput().getType()) &&
2773 "bitcast does not cover entire union");
2774 if (inputWidth == getBitWidth(extractOp.getType())) {
2775 auto loc = FusedLoc::get(rewriter.getContext(),
2776 {bitcastOp.getLoc(), extractOp.getLoc()});
2777 auto newBitcast = rewriter.createOrFold<BitcastOp>(
2778 loc, extractOp.getType(), bitcastOp.getInput());
2779 rewriter.replaceOp(extractOp, newBitcast);
2780 return success();
2781 }
2782 }
2783
2784 return failure();
2785}
2786
2787//===----------------------------------------------------------------------===//
2788// ArrayGetOp
2789//===----------------------------------------------------------------------===//
2790
2791// An array_get of an array_create with a constant index can just be the
2792// array_create operand at the constant index. If the array_create has a
2793// single uniform value for each element, just return that value regardless of
2794// the index. If the array is constructed from a constant by a bitcast
2795// operation, we can fold into a constant.
2796OpFoldResult ArrayGetOp::fold(FoldAdaptor adaptor) {
2797 auto inputCst = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2798 auto indexCst = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2799
2800 if (inputCst) {
2801 // Constant array index.
2802 if (indexCst) {
2803 auto indexVal = indexCst.getValue();
2804 if (indexVal.getBitWidth() < 64) {
2805 auto index = indexVal.getZExtValue();
2806 return inputCst[inputCst.size() - 1 - index];
2807 }
2808 }
2809 // If all elements of the array are the same, we can return any element of
2810 // array.
2811 if (!inputCst.empty() && llvm::all_equal(inputCst))
2812 return inputCst[0];
2813 }
2814
2815 // array_get(bitcast(c), i) -> c[i*w+w-1:i*w]
2816 if (auto bitcast = getInput().getDefiningOp<hw::BitcastOp>()) {
2817 auto intTy = dyn_cast<IntegerType>(getType());
2818 if (!intTy)
2819 return {};
2820 auto bitcastInputOp = bitcast.getInput().getDefiningOp<hw::ConstantOp>();
2821 if (!bitcastInputOp)
2822 return {};
2823 if (!indexCst)
2824 return {};
2825 auto bitcastInputCst = bitcastInputOp.getValue();
2826 // Calculate the index. Make sure to zero-extend the index value before
2827 // multiplying the element width.
2828 auto startIdx = indexCst.getValue().zext(bitcastInputCst.getBitWidth()) *
2829 getType().getIntOrFloatBitWidth();
2830 // Extract [startIdx + width - 1: startIdx].
2831 return IntegerAttr::get(intTy, bitcastInputCst.lshr(startIdx).trunc(
2832 intTy.getIntOrFloatBitWidth()));
2833 }
2834
2835 // array_get(array_inject(_, index, element), index) -> element
2836 if (auto inject = getInput().getDefiningOp<ArrayInjectOp>())
2837 if (getIndex() == inject.getIndex())
2838 return inject.getElement();
2839
2840 auto inputCreate = getInput().getDefiningOp<ArrayCreateOp>();
2841 if (!inputCreate)
2842 return {};
2843
2844 if (auto uniformValue = inputCreate.getUniformElement())
2845 return uniformValue;
2846
2847 if (!indexCst || indexCst.getValue().getBitWidth() > 64)
2848 return {};
2849
2850 uint64_t index = indexCst.getValue().getLimitedValue();
2851 auto createInputs = inputCreate.getInputs();
2852 if (index >= createInputs.size())
2853 return {};
2854 return createInputs[createInputs.size() - index - 1];
2855}
2856
2857LogicalResult ArrayGetOp::canonicalize(ArrayGetOp op,
2858 PatternRewriter &rewriter) {
2859 auto idxOpt = getUIntFromValue(op.getIndex());
2860 if (!idxOpt)
2861 return failure();
2862
2863 auto *inputOp = op.getInput().getDefiningOp();
2864 if (auto inputSlice = dyn_cast_or_null<ArraySliceOp>(inputOp)) {
2865 // get(slice(a, n), m) -> get(a, n + m)
2866 auto offsetOp = inputSlice.getLowIndex();
2867 auto offsetOpt = getUIntFromValue(offsetOp);
2868 if (!offsetOpt)
2869 return failure();
2870
2871 uint64_t offset = *offsetOpt + *idxOpt;
2872 auto newOffset =
2873 ConstantOp::create(rewriter, op.getLoc(), offsetOp.getType(), offset);
2874 rewriter.replaceOpWithNewOp<ArrayGetOp>(op, inputSlice.getInput(),
2875 newOffset);
2876 return success();
2877 }
2878
2879 if (auto inputConcat = dyn_cast_or_null<ArrayConcatOp>(inputOp)) {
2880 // get(concat(a0, a1, ...), m) -> get(an, m - s0 - s1 - ...)
2881 uint64_t elemIndex = *idxOpt;
2882 for (auto input : llvm::reverse(inputConcat.getInputs())) {
2883 size_t size = hw::type_cast<ArrayType>(input.getType()).getNumElements();
2884 if (elemIndex >= size) {
2885 elemIndex -= size;
2886 continue;
2887 }
2888
2889 unsigned indexWidth = size == 1 ? 1 : llvm::Log2_64_Ceil(size);
2890 auto newIdxOp =
2891 ConstantOp::create(rewriter, op.getLoc(),
2892 rewriter.getIntegerType(indexWidth), elemIndex);
2893
2894 rewriter.replaceOpWithNewOp<ArrayGetOp>(op, input, newIdxOp);
2895 return success();
2896 }
2897 return failure();
2898 }
2899
2900 // array_get const, (array_get sel, (array_create a, b, c, d)) -->
2901 // array_get sel, (array_create (array_get const a), (array_get const b),
2902 // (array_get const, c), (array_get const, d))
2903 if (auto innerGet = dyn_cast_or_null<hw::ArrayGetOp>(inputOp)) {
2904 if (!innerGet.getIndex().getDefiningOp<hw::ConstantOp>()) {
2905 if (auto create =
2906 innerGet.getInput().getDefiningOp<hw::ArrayCreateOp>()) {
2907
2908 SmallVector<Value> newValues;
2909 for (auto operand : create.getOperands())
2910 newValues.push_back(rewriter.createOrFold<hw::ArrayGetOp>(
2911 op.getLoc(), operand, op.getIndex()));
2912
2913 rewriter.replaceOpWithNewOp<hw::ArrayGetOp>(
2914 op,
2915 rewriter.createOrFold<hw::ArrayCreateOp>(op.getLoc(), newValues),
2916 innerGet.getIndex());
2917 return success();
2918 }
2919 }
2920 }
2921
2922 return failure();
2923}
2924
2925//===----------------------------------------------------------------------===//
2926// ArrayInjectOp
2927//===----------------------------------------------------------------------===//
2928
2929OpFoldResult ArrayInjectOp::fold(FoldAdaptor adaptor) {
2930 auto inputAttr = dyn_cast_or_null<ArrayAttr>(adaptor.getInput());
2931 auto indexAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getIndex());
2932 auto elementAttr = adaptor.getElement();
2933
2934 // inject(constant[xs, y, zs], iy, a) -> constant[x, a, z]
2935 if (inputAttr && indexAttr && elementAttr) {
2936 if (auto index = indexAttr.getValue().tryZExtValue()) {
2937 if (*index < inputAttr.size()) {
2938 SmallVector<Attribute> elements(inputAttr.getValue());
2939 elements[inputAttr.size() - 1 - *index] = elementAttr;
2940 return ArrayAttr::get(getContext(), elements);
2941 }
2942 }
2943 }
2944
2945 return {};
2946}
2947
2948static LogicalResult canonicalizeArrayInjectChain(ArrayInjectOp op,
2949 PatternRewriter &rewriter) {
2950 // If this inject is only used as an input to another inject, don't try to
2951 // canonicalize it. It will be included in that other op's canonicalization
2952 // attempt. This avoids doing redundant work.
2953 if (op->hasOneUse()) {
2954 auto &use = *op->use_begin();
2955 if (isa<ArrayInjectOp>(use.getOwner()) && use.getOperandNumber() == 0)
2956 return failure();
2957 }
2958
2959 // Collect all injects to constant indices.
2960 auto arrayLength = type_cast<ArrayType>(op.getType()).getNumElements();
2961 Value input = op;
2963 while (auto inject = input.getDefiningOp<ArrayInjectOp>()) {
2964 // Determine the constant index.
2965 APInt indexAPInt;
2966 if (!matchPattern(inject.getIndex(), mlir::m_ConstantInt(&indexAPInt)))
2967 break;
2968 if (indexAPInt.getActiveBits() > 32)
2969 break;
2970 uint32_t index = indexAPInt.getZExtValue();
2971
2972 // Track the injected value. Make sure to only track indices that are in
2973 // bounds. This will allow us to later check if `elements.size()` matches
2974 // the array length.
2975 if (index < arrayLength)
2976 elements.insert({index, inject.getElement()});
2977
2978 // Step to the next inject op.
2979 input = inject.getInput();
2980 if (input == op)
2981 break; // break cycles
2982 }
2983
2984 // If we are assigning every single element, replace the op with an
2985 // `hw.array_create`.
2986 if (elements.size() == arrayLength) {
2987 SmallVector<Value, 4> operands;
2988 operands.reserve(arrayLength);
2989 for (uint32_t idx = 0; idx < arrayLength; ++idx)
2990 operands.push_back(elements.at(arrayLength - idx - 1));
2991 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, op.getType(), operands);
2992 return success();
2993 }
2994
2995 return failure();
2996}
2997
2998static LogicalResult
2999canonicalizeArrayInjectIntoCreate(ArrayInjectOp op, PatternRewriter &rewriter) {
3000 auto createOp = op.getInput().getDefiningOp<ArrayCreateOp>();
3001 if (!createOp)
3002 return failure();
3003
3004 // Make sure the access is in bounds.
3005 APInt indexAPInt;
3006 if (!matchPattern(op.getIndex(), mlir::m_ConstantInt(&indexAPInt)) ||
3007 !indexAPInt.ult(createOp.getInputs().size()))
3008 return failure();
3009
3010 // Substitute the injected value.
3011 SmallVector<Value> elements = createOp.getInputs();
3012 elements[elements.size() - indexAPInt.getZExtValue() - 1] = op.getElement();
3013 rewriter.replaceOpWithNewOp<ArrayCreateOp>(op, elements);
3014 return success();
3015}
3016
3017void ArrayInjectOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
3018 MLIRContext *context) {
3019 patterns.add<ArrayInjectToSameIndex>(context);
3022}
3023
3024//===----------------------------------------------------------------------===//
3025// TypedeclOp
3026//===----------------------------------------------------------------------===//
3027
3028StringRef TypedeclOp::getPreferredName() {
3029 return getVerilogName().value_or(getName());
3030}
3031
3032Type TypedeclOp::getAliasType() {
3033 auto parentScope = cast<hw::TypeScopeOp>(getOperation()->getParentOp());
3034 return hw::TypeAliasType::get(
3035 SymbolRefAttr::get(parentScope.getSymNameAttr(),
3036 {FlatSymbolRefAttr::get(*this)}),
3037 getType());
3038}
3039
3040//===----------------------------------------------------------------------===//
3041// BitcastOp
3042//===----------------------------------------------------------------------===//
3043
3044OpFoldResult BitcastOp::fold(FoldAdaptor adaptor) {
3045 // Identity.
3046 // bitcast(%a) : A -> A ==> %a
3047 if (getOperand().getType() == getType())
3048 return getOperand();
3049
3050 // bitcast(int_constant)
3051 if (auto intAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getInput())) {
3052 ArrayAttr arrVal;
3053 if (succeeded(apIntToAggregateAttr(getType(), intAttr.getValue(), arrVal)))
3054 return arrVal;
3055 }
3056
3057 // bitcast(aggregate_constant)
3058 if (auto arrayAttr = dyn_cast_or_null<ArrayAttr>(adaptor.getInput())) {
3059 APInt intVal;
3060 if (succeeded(
3061 aggregateAttrToAPInt(getInput().getType(), arrayAttr, intVal))) {
3062 if (auto intType = dyn_cast<IntegerType>(getType()))
3063 return IntegerAttr::get(intType, intVal);
3064
3065 ArrayAttr arrVal;
3066 if (succeeded(apIntToAggregateAttr(getType(), intVal, arrVal)))
3067 return arrVal;
3068 }
3069 }
3070 return {};
3071}
3072
3073LogicalResult BitcastOp::canonicalize(BitcastOp op, PatternRewriter &rewriter) {
3074 // Composition.
3075 // %b = bitcast(%a) : A -> B
3076 // bitcast(%b) : B -> C
3077 // ===> bitcast(%a) : A -> C
3078 auto inputBitcast =
3079 dyn_cast_or_null<BitcastOp>(op.getInput().getDefiningOp());
3080 if (!inputBitcast)
3081 return failure();
3082 auto bitcast = rewriter.createOrFold<BitcastOp>(op.getLoc(), op.getType(),
3083 inputBitcast.getInput());
3084 rewriter.replaceOp(op, bitcast);
3085 return success();
3086}
3087
3088LogicalResult BitcastOp::verify() {
3089 if (getBitWidth(getInput().getType()) != getBitWidth(getResult().getType()))
3090 return this->emitOpError("Bitwidth of input must match result");
3091 return success();
3092}
3093
3094//===----------------------------------------------------------------------===//
3095// HierPathOp helpers.
3096//===----------------------------------------------------------------------===//
3097
3098bool HierPathOp::dropModule(StringAttr moduleToDrop) {
3099 SmallVector<Attribute, 4> newPath;
3100 bool updateMade = false;
3101 for (auto nameRef : getNamepath()) {
3102 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3103 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3104 if (ref.getModule() == moduleToDrop)
3105 updateMade = true;
3106 else
3107 newPath.push_back(ref);
3108 } else {
3109 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3110 updateMade = true;
3111 else
3112 newPath.push_back(nameRef);
3113 }
3114 }
3115 if (updateMade)
3116 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3117 return updateMade;
3118}
3119
3120bool HierPathOp::inlineModule(StringAttr moduleToDrop) {
3121 SmallVector<Attribute, 4> newPath;
3122 bool updateMade = false;
3123 StringRef inlinedInstanceName = "";
3124 for (auto nameRef : getNamepath()) {
3125 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3126 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3127 if (ref.getModule() == moduleToDrop) {
3128 inlinedInstanceName = ref.getName().getValue();
3129 updateMade = true;
3130 } else if (!inlinedInstanceName.empty()) {
3131 newPath.push_back(hw::InnerRefAttr::get(
3132 ref.getModule(),
3133 StringAttr::get(getContext(), inlinedInstanceName + "_" +
3134 ref.getName().getValue())));
3135 inlinedInstanceName = "";
3136 } else
3137 newPath.push_back(ref);
3138 } else {
3139 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == moduleToDrop)
3140 updateMade = true;
3141 else
3142 newPath.push_back(nameRef);
3143 }
3144 }
3145 if (updateMade)
3146 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3147 return updateMade;
3148}
3149
3150bool HierPathOp::updateModule(StringAttr oldMod, StringAttr newMod) {
3151 SmallVector<Attribute, 4> newPath;
3152 bool updateMade = false;
3153 for (auto nameRef : getNamepath()) {
3154 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3155 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3156 if (ref.getModule() == oldMod) {
3157 newPath.push_back(hw::InnerRefAttr::get(newMod, ref.getName()));
3158 updateMade = true;
3159 } else
3160 newPath.push_back(ref);
3161 } else {
3162 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == oldMod) {
3163 newPath.push_back(FlatSymbolRefAttr::get(newMod));
3164 updateMade = true;
3165 } else
3166 newPath.push_back(nameRef);
3167 }
3168 }
3169 if (updateMade)
3170 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3171 return updateMade;
3172}
3173
3174bool HierPathOp::updateModuleAndInnerRef(
3175 StringAttr oldMod, StringAttr newMod,
3176 const llvm::DenseMap<StringAttr, StringAttr> &innerSymRenameMap) {
3177 auto fromRef = FlatSymbolRefAttr::get(oldMod);
3178 if (oldMod == newMod)
3179 return false;
3180
3181 auto namepathNew = getNamepath().getValue().vec();
3182 bool updateMade = false;
3183 // Break from the loop if the module is found, since it can occur only once.
3184 for (auto &element : namepathNew) {
3185 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(element)) {
3186 if (innerRef.getModule() != oldMod)
3187 continue;
3188 auto symName = innerRef.getName();
3189 // Since the module got updated, the old innerRef symbol inside oldMod
3190 // should also be updated to the new symbol inside the newMod.
3191 auto to = innerSymRenameMap.find(symName);
3192 if (to != innerSymRenameMap.end())
3193 symName = to->second;
3194 updateMade = true;
3195 element = hw::InnerRefAttr::get(newMod, symName);
3196 break;
3197 }
3198 if (element != fromRef)
3199 continue;
3200
3201 updateMade = true;
3202 element = FlatSymbolRefAttr::get(newMod);
3203 break;
3204 }
3205 if (updateMade)
3206 setNamepathAttr(ArrayAttr::get(getContext(), namepathNew));
3207 return updateMade;
3208}
3209
3210bool HierPathOp::truncateAtModule(StringAttr atMod, bool includeMod) {
3211 SmallVector<Attribute, 4> newPath;
3212 bool updateMade = false;
3213 for (auto nameRef : getNamepath()) {
3214 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3215 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3216 if (ref.getModule() == atMod) {
3217 updateMade = true;
3218 if (includeMod)
3219 newPath.push_back(ref);
3220 } else
3221 newPath.push_back(ref);
3222 } else {
3223 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == atMod && !includeMod)
3224 updateMade = true;
3225 else
3226 newPath.push_back(nameRef);
3227 }
3228 if (updateMade)
3229 break;
3230 }
3231 if (updateMade)
3232 setNamepathAttr(ArrayAttr::get(getContext(), newPath));
3233 return updateMade;
3234}
3235
3236/// Return just the module part of the namepath at a specific index.
3237StringAttr HierPathOp::modPart(unsigned i) {
3238 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3239 .Case<FlatSymbolRefAttr>([](auto a) { return a.getAttr(); })
3240 .Case<hw::InnerRefAttr>([](auto a) { return a.getModule(); });
3241}
3242
3243/// Return the root module.
3244StringAttr HierPathOp::root() {
3245 assert(!getNamepath().empty());
3246 return modPart(0);
3247}
3248
3249/// Return true if the NLA has the module in its path.
3250bool HierPathOp::hasModule(StringAttr modName) {
3251 for (auto nameRef : getNamepath()) {
3252 // nameRef is either an InnerRefAttr or a FlatSymbolRefAttr.
3253 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef)) {
3254 if (ref.getModule() == modName)
3255 return true;
3256 } else {
3257 if (cast<FlatSymbolRefAttr>(nameRef).getAttr() == modName)
3258 return true;
3259 }
3260 }
3261 return false;
3262}
3263
3264/// Return true if the NLA has the InnerSym .
3265bool HierPathOp::hasInnerSym(StringAttr modName, StringAttr symName) const {
3266 for (auto nameRef : const_cast<HierPathOp *>(this)->getNamepath())
3267 if (auto ref = dyn_cast<hw::InnerRefAttr>(nameRef))
3268 if (ref.getName() == symName && ref.getModule() == modName)
3269 return true;
3270
3271 return false;
3272}
3273
3274/// Return just the reference part of the namepath at a specific index. This
3275/// will return an empty attribute if this is the leaf and the leaf is a module.
3276StringAttr HierPathOp::refPart(unsigned i) {
3277 return TypeSwitch<Attribute, StringAttr>(getNamepath()[i])
3278 .Case<FlatSymbolRefAttr>([](auto a) { return StringAttr({}); })
3279 .Case<hw::InnerRefAttr>([](auto a) { return a.getName(); });
3280}
3281
3282/// Return the leaf reference. This returns an empty attribute if the leaf
3283/// reference is a module.
3284StringAttr HierPathOp::ref() {
3285 assert(!getNamepath().empty());
3286 return refPart(getNamepath().size() - 1);
3287}
3288
3289/// Return the leaf module.
3290StringAttr HierPathOp::leafMod() {
3291 assert(!getNamepath().empty());
3292 return modPart(getNamepath().size() - 1);
3293}
3294
3295/// Returns true if this NLA targets an instance of a module (as opposed to
3296/// an instance's port or something inside an instance).
3297bool HierPathOp::isModule() { return !ref(); }
3298
3299/// Returns true if this NLA targets something inside a module (as opposed
3300/// to a module or an instance of a module);
3301bool HierPathOp::isComponent() { return (bool)ref(); }
3302
3303// Verify the HierPathOp.
3304// 1. Iterate over the namepath.
3305// 2. The namepath should be a valid instance path, specified either on a
3306// module or a declaration inside a module.
3307// 3. Each element in the namepath is an InnerRefAttr except possibly the
3308// last element.
3309// 4. Make sure that the InnerRefAttr is legal, by verifying the module name
3310// and the corresponding inner_sym on the instance.
3311// 5. Make sure that the instance path is legal, by verifying the sequence of
3312// instance and the expected module occurs as the next element in the path.
3313// 6. The last element of the namepath, can be an InnerRefAttr on either a
3314// module port or a declaration inside the module.
3315// 7. The last element of the namepath can also be a module symbol.
3316LogicalResult HierPathOp::verifyInnerRefs(hw::InnerRefNamespace &ns) {
3317 ArrayAttr expectedModuleNames = {};
3318 auto checkExpectedModule = [&](Attribute name) -> LogicalResult {
3319 if (!expectedModuleNames)
3320 return success();
3321 if (llvm::any_of(expectedModuleNames,
3322 [name](Attribute attr) { return attr == name; }))
3323 return success();
3324 auto diag = emitOpError() << "instance path is incorrect. Expected ";
3325 size_t n = expectedModuleNames.size();
3326 if (n != 1) {
3327 diag << "one of ";
3328 }
3329 for (size_t i = 0; i < n; ++i) {
3330 if (i != 0)
3331 diag << ((i + 1 == n) ? " or " : ", ");
3332 diag << cast<StringAttr>(expectedModuleNames[i]);
3333 }
3334 diag << ". Instead found: " << name;
3335 return diag;
3336 };
3337
3338 if (!getNamepath() || getNamepath().empty())
3339 return emitOpError() << "the instance path cannot be empty";
3340 for (unsigned i = 0, s = getNamepath().size() - 1; i < s; ++i) {
3341 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(getNamepath()[i]);
3342 if (!innerRef)
3343 return emitOpError()
3344 << "the instance path can only contain inner sym reference"
3345 << ", only the leaf can refer to a module symbol";
3346
3347 if (failed(checkExpectedModule(innerRef.getModule())))
3348 return failure();
3349
3350 auto instOp = ns.lookupOp<igraph::InstanceOpInterface>(innerRef);
3351 if (!instOp)
3352 return emitOpError() << " module: " << innerRef.getModule()
3353 << " does not contain any instance with symbol: "
3354 << innerRef.getName();
3355 expectedModuleNames = instOp.getReferencedModuleNamesAttr();
3356 }
3357
3358 // The instance path has been verified. Now verify the last element.
3359 auto leafRef = getNamepath()[getNamepath().size() - 1];
3360 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(leafRef)) {
3361 if (!ns.lookup(innerRef)) {
3362 return emitOpError() << " operation with symbol: " << innerRef
3363 << " was not found ";
3364 }
3365 if (failed(checkExpectedModule(innerRef.getModule())))
3366 return failure();
3367 } else if (failed(checkExpectedModule(
3368 cast<FlatSymbolRefAttr>(leafRef).getAttr()))) {
3369 return failure();
3370 }
3371 return success();
3372}
3373
3374void HierPathOp::print(OpAsmPrinter &p) {
3375 p << " ";
3376
3377 // Print visibility if present.
3378 StringRef visibilityAttrName =
3379 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
3380 if (auto visibility =
3381 getOperation()->getAttrOfType<StringAttr>(visibilityAttrName))
3382 p << visibility.getValue() << ' ';
3383
3384 p.printSymbolName(getSymName());
3385 p << " [";
3386 llvm::interleaveComma(getNamepath().getValue(), p, [&](Attribute attr) {
3387 if (auto ref = dyn_cast<hw::InnerRefAttr>(attr)) {
3388 p.printSymbolName(ref.getModule().getValue());
3389 p << "::";
3390 p.printSymbolName(ref.getName().getValue());
3391 } else {
3392 p.printSymbolName(cast<FlatSymbolRefAttr>(attr).getValue());
3393 }
3394 });
3395 p << "]";
3396 p.printOptionalAttrDict(
3397 (*this)->getAttrs(),
3398 {getSymNameAttrName(), "namepath", visibilityAttrName});
3399}
3400
3401ParseResult HierPathOp::parse(OpAsmParser &parser, OperationState &result) {
3402 // Parse the visibility attribute.
3403 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
3404
3405 // Parse the symbol name.
3406 StringAttr symName;
3407 if (parser.parseSymbolName(symName, getSymNameAttrName(result.name),
3408 result.attributes))
3409 return failure();
3410
3411 // Parse the namepath.
3412 SmallVector<Attribute> namepath;
3413 if (parser.parseCommaSeparatedList(
3414 OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
3415 auto loc = parser.getCurrentLocation();
3416 SymbolRefAttr ref;
3417 if (parser.parseAttribute(ref))
3418 return failure();
3419
3420 // "A" is a Ref, "A::b" is a InnerRef, "A::B::c" is an error.
3421 auto pathLength = ref.getNestedReferences().size();
3422 if (pathLength == 0)
3423 namepath.push_back(
3424 FlatSymbolRefAttr::get(ref.getRootReference()));
3425 else if (pathLength == 1)
3426 namepath.push_back(hw::InnerRefAttr::get(ref.getRootReference(),
3427 ref.getLeafReference()));
3428 else
3429 return parser.emitError(loc,
3430 "only one nested reference is allowed");
3431 return success();
3432 }))
3433 return failure();
3434 result.addAttribute("namepath",
3435 ArrayAttr::get(parser.getContext(), namepath));
3436
3437 if (parser.parseOptionalAttrDict(result.attributes))
3438 return failure();
3439
3440 return success();
3441}
3442
3443//===----------------------------------------------------------------------===//
3444// TriggeredOp
3445//===----------------------------------------------------------------------===//
3446
3447void TriggeredOp::build(OpBuilder &builder, OperationState &odsState,
3448 EventControlAttr event, Value trigger,
3449 ValueRange inputs) {
3450 odsState.addOperands(trigger);
3451 odsState.addOperands(inputs);
3452 odsState.addAttribute(getEventAttrName(odsState.name), event);
3453 auto *r = odsState.addRegion();
3454 Block *b = new Block();
3455 r->push_back(b);
3456
3457 llvm::SmallVector<Location> argLocs;
3458 llvm::transform(inputs, std::back_inserter(argLocs),
3459 [&](Value v) { return v.getLoc(); });
3460 b->addArguments(inputs.getTypes(), argLocs);
3461}
3462
3463//===----------------------------------------------------------------------===//
3464// TableGen generated logic.
3465//===----------------------------------------------------------------------===//
3466
3467// Provide the autogenerated implementation guts for the Op classes.
3468#define GET_OP_CLASSES
3469#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:1088
static void printParamValue(OpAsmPrinter &p, Operation *, Attribute value, Type resultType)
Definition HWOps.cpp:505
static LogicalResult canonicalizeArrayInjectChain(ArrayInjectOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2948
static void printModuleOp(OpAsmPrinter &p, ModuleTy mod)
Definition HWOps.cpp:1031
static bool flattenConcatOp(ArrayConcatOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2031
static LogicalResult foldCreateToSlice(ArrayCreateOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:1761
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
Definition HWOps.cpp:1453
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:2454
static void printArrayConcatTypes(OpAsmPrinter &p, Operation *, TypeRange inputTypes, Type resultType)
Definition HWOps.cpp:1992
static ParseResult parseSliceTypes(OpAsmParser &p, Type &srcType, Type &idxType)
Definition HWOps.cpp:1648
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:900
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:601
static bool mergeConcatSlices(ArrayConcatOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2048
static SmallVector< Location > getAllPortLocs(ModTy module)
Definition HWOps.cpp:1231
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:2417
static void setAllPortNames(ArrayRef< Attribute > names, ModTy module)
Definition HWOps.cpp:1301
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:1374
static ParseResult parseParamValue(OpAsmParser &p, Attribute &value, Type &resultType)
Definition HWOps.cpp:497
static LogicalResult checkAttributes(Operation *op, Attribute attr, Type type)
Definition HWOps.cpp:411
static LogicalResult canonicalizeArrayInjectIntoCreate(ArrayInjectOp op, PatternRewriter &rewriter)
Definition HWOps.cpp:2999
static std::optional< uint64_t > getUIntFromValue(Value value)
Definition HWOps.cpp:1832
static ParseResult parseHWModuleOp(OpAsmParser &parser, OperationState &result)
Definition HWOps.cpp:908
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:2391
static PortInfo getPort(ModuleTy &mod, size_t idx)
Definition HWOps.cpp:1473
static void printSliceTypes(OpAsmPrinter &p, Operation *, Type srcType, Type idxType)
Definition HWOps.cpp:1662
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:1962
static bool getFieldName(const FieldRef &fieldRef, SmallString< 32 > &string)
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:222
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:86
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:120
llvm::SmallVector< Value > inputArgs
Definition HWOps.h:119
llvm::StringMap< unsigned > outputIdx
Definition HWOps.h:118
llvm::StringMap< unsigned > inputIdx
Definition HWOps.h:118
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:56
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:1176
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:1737
llvm::function_ref< void(OpBuilder &, HWModulePortAccessor &)> HWModuleBuilder
Definition HWOps.h:125
FunctionType getModuleType(Operation *module)
Return the signature for the specified module as a function type.
Definition HWOps.cpp:533
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
LogicalResult aggregateAttrToAPInt(mlir::Type type, ArrayAttr attr, APInt &result)
Convert an ArrayAttr into an APInt value matching the given type.
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:122
bool isAnyModuleOrInstance(Operation *module)
TODO: Move all these functions to a hw::ModuleLike interface.
Definition HWOps.cpp:527
LogicalResult apIntToAggregateAttr(mlir::Type aggregateType, const APInt &intVal, ArrayAttr &result)
Convert an APInt value into a nested aggregate attribute matching the given HWAggregateType.
StringAttr getVerilogModuleNameAttr(Operation *module)
Returns the verilog module name attribute or symbol name of any module-like operations.
Definition HWOps.cpp:551
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:193
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:33
mlir::StringAttr name
Definition HWTypes.h:32
This holds the name, type, direction of a module's ports.