16 #include "mlir/IR/Builders.h"
17 #include "mlir/IR/ImplicitLocOpBuilder.h"
27 auto *context = parser.getContext();
28 auto loc = parser.getCurrentLocation();
30 if (parser.parseString(&rawPath))
33 return parser.emitError(loc,
"invalid base path");
49 StringAttr &module, StringAttr &ref,
52 auto *context = parser.getContext();
53 auto loc = parser.getCurrentLocation();
55 if (parser.parseString(&rawPath))
57 if (
parsePath(context, rawPath, path, module, ref, field))
58 return parser.emitError(loc,
"invalid path");
63 StringAttr module, StringAttr ref,
66 for (
const auto &elt : path)
67 p << elt.module.getValue() <<
'/' << elt.instance.getValue() <<
':';
68 if (!module.getValue().empty())
69 p << module.getValue();
70 if (!ref.getValue().empty())
71 p << '>
' << ref.getValue();
72 if (!field.getValue().empty())
73 p << field.getValue();
77 //===----------------------------------------------------------------------===//
79 //===----------------------------------------------------------------------===//
80 static ParseResult parseClassFieldsList(OpAsmParser &parser,
81 SmallVectorImpl<Attribute> &fieldNames,
82 SmallVectorImpl<Type> &fieldTypes) {
84 llvm::StringMap<SMLoc> nameLocMap;
85 auto parseElt = [&]() -> ParseResult {
86 // Parse the field name.
87 std::string fieldName;
88 if (parser.parseKeywordOrString(&fieldName))
90 SMLoc currLoc = parser.getCurrentLocation();
91 if (nameLocMap.count(fieldName)) {
92 parser.emitError(currLoc, "field \
"")
93 << fieldName <<
"\" is defined twice";
94 parser.emitError(nameLocMap[fieldName]) <<
"previous definition is here";
97 nameLocMap[fieldName] = currLoc;
101 fieldTypes.emplace_back();
102 if (parser.parseColonType(fieldTypes.back()))
108 return parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
115 if (parser.parseSymbolName(symName, mlir::SymbolTable::getSymbolAttrName(),
120 SmallVector<OpAsmParser::Argument> args;
121 if (parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
125 SmallVector<Type> fieldTypes;
126 SmallVector<Attribute> fieldNames;
127 if (succeeded(parser.parseOptionalArrow()))
131 SmallVector<NamedAttribute> fieldTypesMap;
132 if (!fieldNames.empty()) {
133 for (
auto [name, type] : zip(fieldNames, fieldTypes))
134 fieldTypesMap.push_back(
135 NamedAttribute(cast<StringAttr>(name),
TypeAttr::get(type)));
137 auto *ctx = parser.getContext();
139 state.addAttribute(
"fieldTypes",
143 if (failed(parser.parseOptionalAttrDictWithKeyword(state.attributes)))
147 Region *region = state.addRegion();
148 if (parser.parseRegion(*region, args))
153 region->emplaceBlock();
156 auto argNames = llvm::map_range(args, [&](OpAsmParser::Argument arg) {
157 return StringAttr::get(parser.getContext(), arg.ssaName.name.drop_front());
161 ArrayAttr::get(parser.getContext(), SmallVector<Attribute>(argNames)));
169 printer << classLike.getSymName();
172 auto argNames = SmallVector<StringRef>(
173 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
174 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
178 for (
size_t i = 0, e = args.size(); i < e; ++i) {
179 printer <<
'%' << argNames[i] <<
": " << args[i].getType();
185 ArrayRef<Attribute> fieldNames =
186 cast<ArrayAttr>(classLike->getAttr(
"fieldNames")).getValue();
188 if (!fieldNames.empty()) {
190 for (
size_t i = 0, e = fieldNames.size(); i < e; ++i) {
193 StringAttr name = cast<StringAttr>(fieldNames[i]);
194 printer.printKeywordOrString(name.getValue());
196 Type type = classLike.getFieldType(name).value();
197 printer.printType(type);
203 SmallVector<StringRef> elidedAttrs{classLike.getSymNameAttrName(),
204 classLike.getFormalParamNamesAttrName(),
205 "fieldTypes",
"fieldNames"};
206 printer.printOptionalAttrDictWithKeyword(classLike.getOperation()->getAttrs(),
210 printer.printRegion(classLike.getBody(),
false,
216 if (classLike.getFormalParamNames().size() !=
217 classLike.getBodyBlock()->getArguments().size()) {
218 auto error = classLike.emitOpError(
219 "formal parameter name list doesn't match formal parameter value list");
220 error.attachNote(classLike.getLoc())
221 <<
"formal parameter names: " << classLike.getFormalParamNames();
222 error.attachNote(classLike.getLoc())
223 <<
"formal parameter values: "
224 << classLike.getBodyBlock()->getArguments();
234 auto argNames = SmallVector<StringRef>(
235 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
236 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
239 for (
size_t i = 0, e = args.size(); i < e; ++i)
240 setNameFn(args[i], argNames[i]);
249 return NamedAttribute(StringAttr(name),
255 DictionaryAttr fieldTypes = mlir::cast<DictionaryAttr>(
256 classLike.getOperation()->getAttr(
"fieldTypes"));
257 Attribute type = fieldTypes.get(name);
260 return cast<TypeAttr>(type).getValue();
264 AttrTypeReplacer &replacer) {
265 classLike->setAttr(
"fieldTypes", cast<DictionaryAttr>(replacer.replace(
266 classLike.getFieldTypes())));
273 ParseResult circt::om::ClassOp::parse(OpAsmParser &parser,
274 OperationState &state) {
278 circt::om::ClassOp circt::om::ClassOp::buildSimpleClassOp(
279 OpBuilder &odsBuilder, Location loc, Twine name,
280 ArrayRef<StringRef> formalParamNames, ArrayRef<StringRef> fieldNames,
281 ArrayRef<Type> fieldTypes) {
282 circt::om::ClassOp classOp = odsBuilder.create<circt::om::ClassOp>(
283 loc, odsBuilder.getStringAttr(name),
284 odsBuilder.getStrArrayAttr(formalParamNames),
285 odsBuilder.getStrArrayAttr(fieldNames),
286 odsBuilder.getDictionaryAttr(llvm::map_to_vector(
287 llvm::zip(fieldNames, fieldTypes), [&](
auto field) -> NamedAttribute {
288 return NamedAttribute(odsBuilder.getStringAttr(std::get<0>(field)),
291 Block *body = &classOp.getRegion().emplaceBlock();
292 auto prevLoc = odsBuilder.saveInsertionPoint();
293 odsBuilder.setInsertionPointToEnd(body);
294 odsBuilder.create<ClassFieldsOp>(
295 loc, llvm::map_to_vector(fieldTypes, [&](Type type) -> Value {
296 return body->addArgument(type, loc);
298 odsBuilder.restoreInsertionPoint(prevLoc);
303 void circt::om::ClassOp::print(OpAsmPrinter &printer) {
309 LogicalResult circt::om::ClassOp::verifyRegions() {
310 auto fieldsOp = cast<ClassFieldsOp>(this->
getBodyBlock()->getTerminator());
313 if (fieldsOp.getNumOperands() != this->getFieldNames().size()) {
314 auto diag = this->emitOpError()
315 <<
"returns '" << this->getFieldNames().size()
316 <<
"' fields, but its terminator returned '"
317 << fieldsOp.getNumOperands() <<
"' fields";
318 return diag.attachNote(fieldsOp.getLoc()) <<
"see terminator:";
322 auto types = this->getFieldTypes();
323 for (
auto [fieldName, terminatorOperandType] :
324 llvm::zip(this->getFieldNames(), fieldsOp.getOperandTypes())) {
326 if (terminatorOperandType ==
327 cast<TypeAttr>(types.get(cast<StringAttr>(fieldName))).getValue())
330 auto diag = this->emitOpError()
331 <<
"returns different field types than its terminator";
332 return diag.attachNote(fieldsOp.getLoc()) <<
"see terminator:";
338 void circt::om::ClassOp::getAsmBlockArgumentNames(
343 std::optional<mlir::Type>
344 circt::om::ClassOp::getFieldType(mlir::StringAttr field) {
348 void circt::om::ClassOp::replaceFieldTypes(AttrTypeReplacer replacer) {
352 void circt::om::ClassOp::updateFields(
353 mlir::ArrayRef<mlir::Location> newLocations,
354 mlir::ArrayRef<mlir::Value> newValues,
355 mlir::ArrayRef<mlir::Attribute> newNames) {
357 auto fieldsOp = getFieldsOp();
358 assert(fieldsOp &&
"The fields op should exist");
360 SmallVector<Attribute> names(getFieldNamesAttr().getAsRange<StringAttr>());
362 SmallVector<NamedAttribute> fieldTypes(getFieldTypesAttr().getValue());
364 SmallVector<Value> fieldVals(fieldsOp.getFields());
366 Location fieldOpLoc = fieldsOp->getLoc();
369 SmallVector<Location> locations;
370 if (
auto fl = dyn_cast<FusedLoc>(fieldOpLoc)) {
371 auto metadataArr = dyn_cast<ArrayAttr>(fl.getMetadata());
372 assert(metadataArr &&
"Expected the metadata for the fused location");
373 auto r = metadataArr.getAsRange<LocationAttr>();
374 locations.append(r.begin(), r.end());
377 locations.append(names.size(), fieldOpLoc);
381 names.append(newNames.begin(), newNames.end());
382 locations.append(newLocations.begin(), newLocations.end());
383 fieldVals.append(newValues.begin(), newValues.end());
386 for (
auto [v, n] : llvm::zip(newValues, newNames))
387 fieldTypes.emplace_back(
388 NamedAttribute(llvm::cast<StringAttr>(n),
TypeAttr::get(v.getType())));
391 SmallVector<Attribute> locationsAttr;
392 llvm::for_each(locations, [&](Location &l) {
393 locationsAttr.push_back(cast<Attribute>(l));
396 ImplicitLocOpBuilder builder(getLoc(), *
this);
398 setFieldNamesAttr(builder.getArrayAttr(names));
400 setFieldTypesAttr(builder.getDictionaryAttr(fieldTypes));
401 fieldsOp.getFieldsMutable().assign(fieldVals);
403 fieldsOp->setLoc(builder.getFusedLoc(
407 void circt::om::ClassOp::addNewFieldsOp(mlir::OpBuilder &builder,
408 mlir::ArrayRef<Location> locs,
409 mlir::ArrayRef<Value> values) {
412 mlir::SmallVector<Attribute> locAttrs;
413 for (
auto loc : locs) {
414 locAttrs.push_back(cast<Attribute>(LocationAttr(loc)));
418 builder.create<ClassFieldsOp>(
419 builder.getFusedLoc(locs, builder.getArrayAttr(locAttrs)), values);
422 mlir::Location circt::om::ClassOp::getFieldLocByIndex(
size_t i) {
423 Location loc = this->getFieldsOp()->getLoc();
424 if (
auto locs = dyn_cast<FusedLoc>(loc)) {
428 ArrayAttr metadataArr = dyn_cast<ArrayAttr>(locs.getMetadata());
429 assert(metadataArr &&
"Expected fused loc to store metadata array");
430 assert(i < metadataArr.size() &&
431 "expected index to be less than array size");
432 LocationAttr locAttr = dyn_cast<LocationAttr>(metadataArr[i]);
433 assert(locAttr &&
"expected metadataArr entry to be location attribute");
434 loc = Location(locAttr);
443 ParseResult circt::om::ClassExternOp::parse(OpAsmParser &parser,
444 OperationState &state) {
448 void circt::om::ClassExternOp::print(OpAsmPrinter &printer) {
458 return this->emitOpError(
"external class body should be empty");
464 void circt::om::ClassExternOp::getAsmBlockArgumentNames(
469 std::optional<mlir::Type>
470 circt::om::ClassExternOp::getFieldType(mlir::StringAttr field) {
474 void circt::om::ClassExternOp::replaceFieldTypes(AttrTypeReplacer replacer) {
482 void circt::om::ObjectOp::build(::mlir::OpBuilder &odsBuilder,
483 ::mlir::OperationState &odsState,
485 ::mlir::ValueRange actualParams) {
486 return build(odsBuilder, odsState,
489 classOp.getNameAttr(), actualParams);
493 circt::om::ObjectOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
495 StringAttr resultClassName = getResult().getType().getClassName().getAttr();
496 StringAttr className = getClassNameAttr();
497 if (resultClassName != className)
498 return emitOpError(
"result type (")
499 << resultClassName <<
") does not match referred to class ("
503 auto classDef = dyn_cast_or_null<ClassLike>(
504 symbolTable.lookupNearestSymbolFrom(*
this, className));
506 return emitOpError(
"refers to non-existant class (") << className <<
')';
508 auto actualTypes = getActualParams().getTypes();
509 auto formalTypes = classDef.getBodyBlock()->getArgumentTypes();
512 if (actualTypes.size() != formalTypes.size()) {
513 auto error = emitOpError(
514 "actual parameter list doesn't match formal parameter list");
515 error.attachNote(classDef.getLoc())
516 <<
"formal parameters: " << classDef.getBodyBlock()->getArguments();
517 error.attachNote(getLoc()) <<
"actual parameters: " << getActualParams();
522 for (
size_t i = 0, e = actualTypes.size(); i < e; ++i) {
523 if (actualTypes[i] != formalTypes[i]) {
524 return emitOpError(
"actual parameter type (")
525 << actualTypes[i] <<
") doesn't match formal parameter type ("
526 << formalTypes[i] <<
')';
537 void circt::om::ConstantOp::build(::mlir::OpBuilder &odsBuilder,
538 ::mlir::OperationState &odsState,
539 ::mlir::TypedAttr constVal) {
540 return build(odsBuilder, odsState, constVal.getType(), constVal);
543 OpFoldResult circt::om::ConstantOp::fold(FoldAdaptor adaptor) {
544 assert(adaptor.getOperands().empty() &&
"constant has no operands");
545 return getValueAttr();
552 void circt::om::ListCreateOp::print(OpAsmPrinter &p) {
554 p.printOperands(getInputs());
555 p.printOptionalAttrDict((*this)->getAttrs());
556 p <<
" : " << getType().getElementType();
559 ParseResult circt::om::ListCreateOp::parse(OpAsmParser &parser,
560 OperationState &result) {
561 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
564 if (parser.parseOperandList(operands) ||
565 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
566 parser.parseType(elemType))
570 for (
auto operand : operands)
571 if (parser.resolveOperand(operand, elemType, result.operands))
580 LogicalResult TupleCreateOp::inferReturnTypes(
581 MLIRContext *context, std::optional<Location> location, ValueRange operands,
582 DictionaryAttr attributes, OpaqueProperties, RegionRange regions,
583 llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
584 ::llvm::SmallVector<Type> types;
585 for (
auto op : operands)
586 types.push_back(op.getType());
595 LogicalResult TupleGetOp::inferReturnTypes(
596 MLIRContext *context, std::optional<Location> location, ValueRange operands,
597 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
598 llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
599 Adaptor adaptor(operands, attributes, properties, regions);
600 auto idx = adaptor.getIndexAttr();
601 if (operands.empty() || !idx)
604 auto tupleTypes = cast<TupleType>(adaptor.getInput().getType()).getTypes();
605 if (tupleTypes.size() <= idx.getValue().getLimitedValue()) {
607 mlir::emitError(*location,
608 "tuple index out-of-bounds, must be less than ")
609 << tupleTypes.size() <<
" but got "
610 << idx.getValue().getLimitedValue();
614 inferredReturnTypes.push_back(tupleTypes[idx.getValue().getLimitedValue()]);
622 void circt::om::MapCreateOp::print(OpAsmPrinter &p) {
624 p.printOperands(getInputs());
625 p.printOptionalAttrDict((*this)->getAttrs());
626 p <<
" : " << cast<circt::om::MapType>(getType()).getKeyType() <<
", "
627 << cast<circt::om::MapType>(getType()).getValueType();
630 ParseResult circt::om::MapCreateOp::parse(OpAsmParser &parser,
631 OperationState &result) {
632 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
635 if (parser.parseOperandList(operands) ||
636 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
637 parser.parseType(
elementType) || parser.parseComma() ||
638 parser.parseType(valueType))
644 for (
auto operand : operands)
645 if (parser.resolveOperand(operand, operandType, result.operands))
655 BasePathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
656 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
657 *
this, getTargetAttr());
659 return emitOpError(
"invalid symbol reference");
668 PathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
669 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
670 *
this, getTargetAttr());
672 return emitOpError(
"invalid symbol reference");
680 FailureOr<llvm::APSInt>
681 IntegerAddOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
682 const llvm::APSInt &rhs) {
683 return success(lhs + rhs);
690 FailureOr<llvm::APSInt>
691 IntegerMulOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
692 const llvm::APSInt &rhs) {
693 return success(lhs * rhs);
700 FailureOr<llvm::APSInt>
701 IntegerShrOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
702 const llvm::APSInt &rhs) {
704 if (!rhs.isNonNegative())
705 return emitOpError(
"shift amount must be non-negative");
707 if (!rhs.isRepresentableByInt64())
708 return emitOpError(
"shift amount must be representable in 64 bits");
709 return success(lhs >> rhs.getExtValue());
716 FailureOr<llvm::APSInt>
717 IntegerShlOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
718 const llvm::APSInt &rhs) {
720 if (!rhs.isNonNegative())
721 return emitOpError(
"shift amount must be non-negative");
723 if (!rhs.isRepresentableByInt64())
724 return emitOpError(
"shift amount must be representable in 64 bits");
725 return success(lhs << rhs.getExtValue());
732 #define GET_OP_CLASSES
733 #include "circt/Dialect/OM/OM.cpp.inc"
assert(baseType &&"element must be base type")
static InstancePath empty
static ParseResult parseClassLike(OpAsmParser &parser, OperationState &state)
LogicalResult verifyClassLike(ClassLike classLike)
void getClassLikeAsmBlockArgumentNames(ClassLike classLike, Region ®ion, OpAsmSetValueNameFn setNameFn)
static ParseResult parseBasePathString(OpAsmParser &parser, PathAttr &path)
static ParseResult parsePathString(OpAsmParser &parser, PathAttr &path, StringAttr &module, StringAttr &ref, StringAttr &field)
static void printBasePathString(OpAsmPrinter &p, Operation *op, PathAttr path)
std::optional< Type > getClassLikeFieldType(ClassLike classLike, StringAttr name)
static ParseResult parseClassFieldsList(OpAsmParser &parser, SmallVectorImpl< Attribute > &fieldNames, SmallVectorImpl< Type > &fieldTypes)
static void printClassLike(ClassLike classLike, OpAsmPrinter &printer)
void replaceClassLikeFieldTypes(ClassLike classLike, AttrTypeReplacer &replacer)
NamedAttribute makeFieldType(StringAttr name, Type type)
NamedAttribute makeFieldIdx(MLIRContext *ctx, mlir::StringAttr name, unsigned i)
static void printPathString(OpAsmPrinter &p, Operation *op, PathAttr path, StringAttr module, StringAttr ref, StringAttr field)
static Block * getBodyBlock(FModuleLike mod)
static LogicalResult verify(Value clock, bool eventExists, mlir::Location loc)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
ParseResult parsePath(MLIRContext *context, StringRef spelling, PathAttr &path, StringAttr &module, StringAttr &ref, StringAttr &field)
Parse a target string in to a path.
ParseResult parseBasePath(MLIRContext *context, StringRef spelling, PathAttr &path)
Parse a target string of the form "Foo/bar:Bar/baz" in to a base path.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
A module name, and the name of an instance inside that module.
mlir::StringAttr instance