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