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