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");
42 p << elt.module.getValue() <<
'/' << elt.
instance.getValue();
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();
77static ParseResult
parseFieldLocs(OpAsmParser &parser, ArrayAttr &fieldLocs) {
78 if (parser.parseOptionalKeyword(
"field_locs"))
80 if (parser.parseLParen() || parser.parseAttribute(fieldLocs) ||
81 parser.parseRParen()) {
88 ArrayAttr fieldLocs) {
89 mlir::OpPrintingFlags flags;
90 if (!flags.shouldPrintDebugInfo() || !fieldLocs)
92 printer <<
"field_locs(";
93 printer.printAttribute(fieldLocs);
101 SmallVectorImpl<Attribute> &fieldNames,
102 SmallVectorImpl<Type> &fieldTypes) {
104 llvm::StringMap<SMLoc> nameLocMap;
105 auto parseElt = [&]() -> ParseResult {
107 std::string fieldName;
108 if (parser.parseKeywordOrString(&fieldName))
110 SMLoc currLoc = parser.getCurrentLocation();
111 if (nameLocMap.count(fieldName)) {
112 parser.emitError(currLoc,
"field \"")
113 << fieldName <<
"\" is defined twice";
114 parser.emitError(nameLocMap[fieldName]) <<
"previous definition is here";
117 nameLocMap[fieldName] = currLoc;
118 fieldNames.push_back(StringAttr::get(parser.getContext(), fieldName));
121 fieldTypes.emplace_back();
122 if (parser.parseColonType(fieldTypes.back()))
128 return parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
135 if (parser.parseSymbolName(symName, mlir::SymbolTable::getSymbolAttrName(),
140 SmallVector<OpAsmParser::Argument> args;
141 if (parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
145 SmallVector<Type> fieldTypes;
146 SmallVector<Attribute> fieldNames;
147 if (succeeded(parser.parseOptionalArrow()))
151 SmallVector<NamedAttribute> fieldTypesMap;
152 if (!fieldNames.empty()) {
153 for (
auto [name, type] : zip(fieldNames, fieldTypes))
154 fieldTypesMap.push_back(
155 NamedAttribute(cast<StringAttr>(name), TypeAttr::get(type)));
157 auto *ctx = parser.getContext();
158 state.addAttribute(
"fieldNames", mlir::ArrayAttr::get(ctx, fieldNames));
159 state.addAttribute(
"fieldTypes",
160 mlir::DictionaryAttr::get(ctx, fieldTypesMap));
163 if (failed(parser.parseOptionalAttrDictWithKeyword(state.attributes)))
167 Region *region = state.addRegion();
168 if (parser.parseRegion(*region, args))
173 region->emplaceBlock();
176 auto argNames = llvm::map_range(args, [&](OpAsmParser::Argument arg) {
177 return StringAttr::get(parser.getContext(), arg.ssaName.name.drop_front());
181 ArrayAttr::get(parser.getContext(), SmallVector<Attribute>(argNames)));
189 printer << classLike.getSymName();
192 auto argNames = SmallVector<StringRef>(
193 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
194 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
198 for (
size_t i = 0, e = args.size(); i < e; ++i) {
199 printer <<
'%' << argNames[i] <<
": " << args[i].getType();
205 ArrayRef<Attribute> fieldNames =
206 cast<ArrayAttr>(classLike->getAttr(
"fieldNames")).getValue();
208 if (!fieldNames.empty()) {
210 for (
size_t i = 0, e = fieldNames.size(); i < e; ++i) {
213 StringAttr name = cast<StringAttr>(fieldNames[i]);
214 printer.printKeywordOrString(name.getValue());
216 Type type = classLike.getFieldType(name).value();
217 printer.printType(type);
223 SmallVector<StringRef> elidedAttrs{classLike.getSymNameAttrName(),
224 classLike.getFormalParamNamesAttrName(),
225 "fieldTypes",
"fieldNames"};
226 printer.printOptionalAttrDictWithKeyword(classLike.getOperation()->getAttrs(),
230 printer.printRegion(classLike.getBody(),
false,
236 if (classLike.getFormalParamNames().size() !=
237 classLike.getBodyBlock()->getArguments().size()) {
238 auto error = classLike.emitOpError(
239 "formal parameter name list doesn't match formal parameter value list");
240 error.attachNote(classLike.getLoc())
241 <<
"formal parameter names: " << classLike.getFormalParamNames();
242 error.attachNote(classLike.getLoc())
243 <<
"formal parameter values: "
244 << classLike.getBodyBlock()->getArguments();
254 auto argNames = SmallVector<StringRef>(
255 classLike.getFormalParamNames().getAsValueRange<StringAttr>());
256 ArrayRef<BlockArgument> args = classLike.getBodyBlock()->getArguments();
259 for (
size_t i = 0, e = args.size(); i < e; ++i)
260 setNameFn(args[i], argNames[i]);
264 return NamedAttribute(name, TypeAttr::get(type));
269 return NamedAttribute(StringAttr(name),
270 mlir::IntegerAttr::get(mlir::IndexType::get(ctx), i));
275 DictionaryAttr fieldTypes = mlir::cast<DictionaryAttr>(
276 classLike.getOperation()->getAttr(
"fieldTypes"));
277 Attribute type = fieldTypes.get(name);
280 return cast<TypeAttr>(type).getValue();
284 AttrTypeReplacer &replacer) {
285 classLike->setAttr(
"fieldTypes", cast<DictionaryAttr>(replacer.replace(
286 classLike.getFieldTypes())));
293ParseResult circt::om::ClassOp::parse(OpAsmParser &parser,
294 OperationState &state) {
298circt::om::ClassOp circt::om::ClassOp::buildSimpleClassOp(
299 OpBuilder &odsBuilder, Location loc, Twine name,
300 ArrayRef<StringRef> formalParamNames, ArrayRef<StringRef> fieldNames,
301 ArrayRef<Type> fieldTypes) {
302 circt::om::ClassOp classOp = odsBuilder.create<circt::om::ClassOp>(
303 loc, odsBuilder.getStringAttr(name),
304 odsBuilder.getStrArrayAttr(formalParamNames),
305 odsBuilder.getStrArrayAttr(fieldNames),
306 odsBuilder.getDictionaryAttr(llvm::map_to_vector(
307 llvm::zip(fieldNames, fieldTypes), [&](
auto field) -> NamedAttribute {
308 return NamedAttribute(odsBuilder.getStringAttr(std::get<0>(field)),
309 TypeAttr::get(std::get<1>(field)));
311 Block *body = &classOp.getRegion().emplaceBlock();
312 auto prevLoc = odsBuilder.saveInsertionPoint();
313 odsBuilder.setInsertionPointToEnd(body);
315 mlir::SmallVector<Attribute> locAttrs(fieldNames.size(), LocationAttr(loc));
317 odsBuilder.create<ClassFieldsOp>(
321 [&](Type type) -> Value {
return body->addArgument(type, loc); }),
322 odsBuilder.getArrayAttr(locAttrs));
324 odsBuilder.restoreInsertionPoint(prevLoc);
329void circt::om::ClassOp::print(OpAsmPrinter &printer) {
333LogicalResult circt::om::ClassOp::verify() {
return verifyClassLike(*
this); }
335LogicalResult circt::om::ClassOp::verifyRegions() {
336 auto fieldsOp = cast<ClassFieldsOp>(this->
getBodyBlock()->getTerminator());
339 if (fieldsOp.getNumOperands() != this->getFieldNames().size()) {
340 auto diag = this->emitOpError()
341 <<
"returns '" << this->getFieldNames().size()
342 <<
"' fields, but its terminator returned '"
343 << fieldsOp.getNumOperands() <<
"' fields";
344 return diag.attachNote(fieldsOp.getLoc()) <<
"see terminator:";
348 auto types = this->getFieldTypes();
349 for (
auto [fieldName, terminatorOperandType] :
350 llvm::zip(this->getFieldNames(), fieldsOp.getOperandTypes())) {
352 if (terminatorOperandType ==
353 cast<TypeAttr>(types.get(cast<StringAttr>(fieldName))).getValue())
356 auto diag = this->emitOpError()
357 <<
"returns different field types than its terminator";
358 return diag.attachNote(fieldsOp.getLoc()) <<
"see terminator:";
364void circt::om::ClassOp::getAsmBlockArgumentNames(
369std::optional<mlir::Type>
370circt::om::ClassOp::getFieldType(mlir::StringAttr field) {
374void circt::om::ClassOp::replaceFieldTypes(AttrTypeReplacer replacer) {
378void circt::om::ClassOp::updateFields(
379 mlir::ArrayRef<mlir::Location> newLocations,
380 mlir::ArrayRef<mlir::Value> newValues,
381 mlir::ArrayRef<mlir::Attribute> newNames) {
383 auto fieldsOp = getFieldsOp();
384 assert(fieldsOp &&
"The fields op should exist");
386 SmallVector<Attribute> names(getFieldNamesAttr().getAsRange<StringAttr>());
388 SmallVector<NamedAttribute> fieldTypes(getFieldTypesAttr().getValue());
390 SmallVector<Value> fieldVals(fieldsOp.getFields());
392 Location fieldOpLoc = fieldsOp->getLoc();
395 SmallVector<Location> locations;
396 if (
auto fl = dyn_cast<FusedLoc>(fieldOpLoc)) {
397 auto metadataArr = dyn_cast<ArrayAttr>(fl.getMetadata());
398 assert(metadataArr &&
"Expected the metadata for the fused location");
399 auto r = metadataArr.getAsRange<LocationAttr>();
400 locations.append(r.begin(), r.end());
403 locations.append(names.size(), fieldOpLoc);
407 names.append(newNames.begin(), newNames.end());
408 locations.append(newLocations.begin(), newLocations.end());
409 fieldVals.append(newValues.begin(), newValues.end());
412 for (
auto [v, n] :
llvm::zip(newValues, newNames))
413 fieldTypes.emplace_back(
414 NamedAttribute(
llvm::cast<StringAttr>(n), TypeAttr::
get(v.getType())));
417 SmallVector<Attribute> locationsAttr;
418 llvm::for_each(locations, [&](Location &l) {
419 locationsAttr.push_back(cast<Attribute>(l));
422 ImplicitLocOpBuilder builder(
getLoc(), *
this);
424 setFieldNamesAttr(builder.getArrayAttr(names));
426 setFieldTypesAttr(builder.getDictionaryAttr(fieldTypes));
427 fieldsOp.getFieldsMutable().assign(fieldVals);
429 fieldsOp->setLoc(builder.getFusedLoc(
430 locations, ArrayAttr::get(getContext(), locationsAttr)));
433void circt::om::ClassOp::addNewFieldsOp(mlir::OpBuilder &builder,
434 mlir::ArrayRef<Location> locs,
435 mlir::ArrayRef<Value> values) {
438 assert(locs.size() == values.size() &&
"Expected a location per value");
439 mlir::SmallVector<Attribute> locAttrs;
440 for (
auto loc : locs) {
441 locAttrs.push_back(cast<Attribute>(LocationAttr(loc)));
445 builder.create<ClassFieldsOp>(builder.getFusedLoc(locs), values,
446 builder.getArrayAttr(locAttrs));
449mlir::Location circt::om::ClassOp::getFieldLocByIndex(
size_t i) {
450 auto fieldsOp = this->getFieldsOp();
451 auto fieldLocs = fieldsOp.getFieldLocs();
452 if (!fieldLocs.has_value())
453 return fieldsOp.getLoc();
454 assert(i < fieldLocs.value().size() &&
455 "field index too large for location array");
456 return cast<LocationAttr>(fieldLocs.value()[i]);
463ParseResult circt::om::ClassExternOp::parse(OpAsmParser &parser,
464 OperationState &state) {
468void circt::om::ClassExternOp::print(OpAsmPrinter &printer) {
472LogicalResult circt::om::ClassExternOp::verify() {
478 return this->emitOpError(
"external class body should be empty");
484void circt::om::ClassExternOp::getAsmBlockArgumentNames(
489std::optional<mlir::Type>
490circt::om::ClassExternOp::getFieldType(mlir::StringAttr field) {
494void circt::om::ClassExternOp::replaceFieldTypes(AttrTypeReplacer replacer) {
502LogicalResult circt::om::ClassFieldsOp::verify() {
503 auto fieldLocs = this->getFieldLocs();
504 if (fieldLocs.has_value()) {
505 auto fieldLocsVal = fieldLocs.value();
506 if (fieldLocsVal.size() != this->getFields().size()) {
507 auto error = this->emitOpError(
"size of field_locs (")
508 << fieldLocsVal.size()
509 <<
") does not match number of fields ("
510 << this->getFields().size() <<
")";
520void circt::om::ObjectOp::build(::mlir::OpBuilder &odsBuilder,
521 ::mlir::OperationState &odsState,
523 ::mlir::ValueRange actualParams) {
524 return build(odsBuilder, odsState,
525 om::ClassType::get(odsBuilder.getContext(),
526 mlir::FlatSymbolRefAttr::get(classOp)),
527 classOp.getNameAttr(), actualParams);
531circt::om::ObjectOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
533 StringAttr resultClassName = getResult().getType().getClassName().getAttr();
534 StringAttr className = getClassNameAttr();
535 if (resultClassName != className)
536 return emitOpError(
"result type (")
537 << resultClassName <<
") does not match referred to class ("
541 auto classDef = dyn_cast_or_null<ClassLike>(
542 symbolTable.lookupNearestSymbolFrom(*
this, className));
544 return emitOpError(
"refers to non-existant class (") << className <<
')';
546 auto actualTypes = getActualParams().getTypes();
547 auto formalTypes = classDef.getBodyBlock()->getArgumentTypes();
550 if (actualTypes.size() != formalTypes.size()) {
551 auto error = emitOpError(
552 "actual parameter list doesn't match formal parameter list");
553 error.attachNote(classDef.getLoc())
554 <<
"formal parameters: " << classDef.getBodyBlock()->getArguments();
555 error.attachNote(
getLoc()) <<
"actual parameters: " << getActualParams();
560 for (
size_t i = 0, e = actualTypes.size(); i < e; ++i) {
561 if (actualTypes[i] != formalTypes[i]) {
562 return emitOpError(
"actual parameter type (")
563 << actualTypes[i] <<
") doesn't match formal parameter type ("
564 << formalTypes[i] <<
')';
575void circt::om::ConstantOp::build(::mlir::OpBuilder &odsBuilder,
576 ::mlir::OperationState &odsState,
577 ::mlir::TypedAttr constVal) {
578 return build(odsBuilder, odsState, constVal.getType(), constVal);
581OpFoldResult circt::om::ConstantOp::fold(FoldAdaptor adaptor) {
582 assert(adaptor.getOperands().empty() &&
"constant has no operands");
583 return getValueAttr();
590void circt::om::ListCreateOp::print(OpAsmPrinter &p) {
592 p.printOperands(getInputs());
593 p.printOptionalAttrDict((*this)->getAttrs());
594 p <<
" : " << getType().getElementType();
597ParseResult circt::om::ListCreateOp::parse(OpAsmParser &parser,
598 OperationState &result) {
599 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
602 if (parser.parseOperandList(operands) ||
603 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
604 parser.parseType(elemType))
606 result.addTypes({circt::om::ListType::get(elemType)});
608 for (
auto operand : operands)
609 if (parser.resolveOperand(operand, elemType, result.operands))
618LogicalResult TupleCreateOp::inferReturnTypes(
619 MLIRContext *context, std::optional<Location> location, ValueRange operands,
620 DictionaryAttr attributes, OpaqueProperties, RegionRange regions,
621 llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
622 ::llvm::SmallVector<Type> types;
623 for (
auto op : operands)
624 types.push_back(op.getType());
625 inferredReturnTypes.push_back(TupleType::get(context, types));
633LogicalResult TupleGetOp::inferReturnTypes(
634 MLIRContext *context, std::optional<Location> location, ValueRange operands,
635 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
636 llvm::SmallVectorImpl<Type> &inferredReturnTypes) {
637 Adaptor adaptor(operands, attributes, properties, regions);
638 auto idx = adaptor.getIndexAttr();
639 if (operands.empty() || !idx)
642 auto tupleTypes = cast<TupleType>(adaptor.getInput().getType()).getTypes();
643 if (tupleTypes.size() <= idx.getValue().getLimitedValue()) {
645 mlir::emitError(*location,
646 "tuple index out-of-bounds, must be less than ")
647 << tupleTypes.size() <<
" but got "
648 << idx.getValue().getLimitedValue();
652 inferredReturnTypes.push_back(tupleTypes[idx.getValue().getLimitedValue()]);
660void circt::om::MapCreateOp::print(OpAsmPrinter &p) {
662 p.printOperands(getInputs());
663 p.printOptionalAttrDict((*this)->getAttrs());
664 p <<
" : " << cast<circt::om::MapType>(getType()).getKeyType() <<
", "
665 << cast<circt::om::MapType>(getType()).getValueType();
668ParseResult circt::om::MapCreateOp::parse(OpAsmParser &parser,
669 OperationState &result) {
670 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
673 if (parser.parseOperandList(operands) ||
674 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
675 parser.parseType(
elementType) || parser.parseComma() ||
676 parser.parseType(valueType))
678 result.addTypes({circt::om::MapType::get(
elementType, valueType)});
680 mlir::TupleType::get(valueType.getContext(), {elementType, valueType});
682 for (
auto operand : operands)
683 if (parser.resolveOperand(operand, operandType, result.operands))
693BasePathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
694 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
695 *
this, getTargetAttr());
697 return emitOpError(
"invalid symbol reference");
706PathCreateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
707 auto hierPath = symbolTable.lookupNearestSymbolFrom<hw::HierPathOp>(
708 *
this, getTargetAttr());
710 return emitOpError(
"invalid symbol reference");
718FailureOr<llvm::APSInt>
719IntegerAddOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
720 const llvm::APSInt &rhs) {
721 return success(lhs + rhs);
728FailureOr<llvm::APSInt>
729IntegerMulOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
730 const llvm::APSInt &rhs) {
731 return success(lhs * rhs);
738FailureOr<llvm::APSInt>
739IntegerShrOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
740 const llvm::APSInt &rhs) {
742 if (!rhs.isNonNegative())
743 return emitOpError(
"shift amount must be non-negative");
745 if (!rhs.isRepresentableByInt64())
746 return emitOpError(
"shift amount must be representable in 64 bits");
747 return success(lhs >> rhs.getExtValue());
754FailureOr<llvm::APSInt>
755IntegerShlOp::evaluateIntegerOperation(
const llvm::APSInt &lhs,
756 const llvm::APSInt &rhs) {
758 if (!rhs.isNonNegative())
759 return emitOpError(
"shift amount must be non-negative");
761 if (!rhs.isRepresentableByInt64())
762 return emitOpError(
"shift amount must be representable in 64 bits");
763 return success(lhs << rhs.getExtValue());
770#define GET_OP_CLASSES
771#include "circt/Dialect/OM/OM.cpp.inc"
assert(baseType &&"element must be base type")
static InstancePath empty
static Location getLoc(DefSlot slot)
static ParseResult parseClassLike(OpAsmParser &parser, OperationState &state)
LogicalResult verifyClassLike(ClassLike classLike)
std::optional< Type > getClassLikeFieldType(ClassLike classLike, StringAttr name)
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)
static void printFieldLocs(OpAsmPrinter &printer, Operation *op, ArrayAttr fieldLocs)
static ParseResult parseFieldLocs(OpAsmParser &parser, ArrayAttr &fieldLocs)
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)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
void error(Twine message)
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 mlir::StringAttr instance