18#include "mlir/IR/IRMapping.h"
19#include "mlir/IR/PatternMatch.h"
20#include "mlir/Interfaces/FunctionImplementation.h"
21#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/TypeSwitch.h"
32 Operation *operation, ArrayAttr argNames,
33 std::function<
void(mlir::InFlightDiagnostic &)> attachNote) {
34 DenseMap<StringRef, BlockArgument> portNames;
35 DenseMap<StringRef, Operation *> memberNames;
36 DenseMap<StringRef, Operation *> localNames;
38 if (operation->getNumRegions() != 1)
39 return operation->emitError(
"required to have exactly one region");
41 bool portsVerified =
true;
43 for (
auto arg : llvm::zip(argNames, operation->getRegion(0).getArguments())) {
44 StringRef argName = cast<StringAttr>(std::get<0>(arg)).getValue();
45 BlockArgument argValue = std::get<1>(arg);
47 if (portNames.count(argName)) {
48 auto diag = mlir::emitError(argValue.getLoc(),
"redefines name '")
50 diag.attachNote(portNames[argName].
getLoc())
51 <<
"'" << argName <<
"' first defined here";
53 portsVerified =
false;
57 portNames.insert({argName, argValue});
61 operation->walk<mlir::WalkOrder::PreOrder>([&](Operation *op) {
62 if (isa<SCModuleOp>(op->getParentOp()))
65 if (
auto nameDeclOp = dyn_cast<SystemCNameDeclOpInterface>(op)) {
66 StringRef name = nameDeclOp.getName();
68 auto reportNameRedefinition = [&](Location firstLoc) -> WalkResult {
69 auto diag = mlir::emitError(op->getLoc(),
"redefines name '")
71 diag.attachNote(firstLoc) <<
"'" << name <<
"' first defined here";
73 return WalkResult::interrupt();
76 if (portNames.count(name))
77 return reportNameRedefinition(portNames[name].
getLoc());
78 if (memberNames.count(name))
79 return reportNameRedefinition(memberNames[name]->
getLoc());
80 if (localNames.count(name))
81 return reportNameRedefinition(localNames[name]->
getLoc());
83 if (isa<SCModuleOp>(op->getParentOp()))
84 memberNames.insert({name, op});
86 localNames.insert({name, op});
89 return WalkResult::advance();
92 if (result.wasInterrupted() || !portsVerified)
103 return TypeSwitch<Type, hw::ModulePort::Direction>(type)
104 .Case<InOutType>([](
auto ty) {
return hw::ModulePort::Direction::InOut; })
105 .Case<InputType>([](
auto ty) {
return hw::ModulePort::Direction::Input; })
107 [](
auto ty) {
return hw::ModulePort::Direction::Output; });
110SCModuleOp::PortDirectionRange
112 std::function<bool(
const BlockArgument &)> predicateFn =
113 [&](
const BlockArgument &arg) ->
bool {
116 return llvm::make_filter_range(getArguments(), predicateFn);
119SmallVector<::circt::hw::PortInfo> SCModuleOp::getPortList() {
120 SmallVector<hw::PortInfo> ports;
121 size_t inputIdx = 0, outputIdx = 0;
122 for (
int i = 0, e = getNumArguments(); i < e; ++i) {
124 auto argType = getArgument(i).getType();
125 info.name = cast<StringAttr>(getPortNames()[i]);
128 info.argNum =
info.dir == hw::ModulePort::Direction::Output ? outputIdx++
130 ports.push_back(info);
135mlir::Region *SCModuleOp::getCallableRegion() {
return &getBody(); }
137StringRef SCModuleOp::getModuleName() {
return getSymName(); }
139ParseResult SCModuleOp::parse(OpAsmParser &parser, OperationState &result) {
142 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
145 StringAttr moduleName;
146 if (parser.parseSymbolName(moduleName,
147 SCModuleOp::getSymNameAttrName(result.name),
152 bool isVariadic =
false;
153 SmallVector<OpAsmParser::Argument, 4> entryArgs;
154 SmallVector<Attribute> argNames;
155 SmallVector<Attribute> argLocs;
156 SmallVector<Attribute> resultNames;
157 SmallVector<DictionaryAttr> resultAttrs;
158 SmallVector<Attribute> resultLocs;
159 TypeAttr functionType;
161 parser, isVariadic, entryArgs, argNames, argLocs, resultNames,
162 resultAttrs, resultLocs, functionType)))
166 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
169 result.addAttribute(
"portNames",
170 ArrayAttr::get(parser.getContext(), argNames));
172 result.addAttribute(SCModuleOp::getFunctionTypeAttrName(result.name),
175 mlir::call_interface_impl::addArgAndResultAttrs(
176 parser.getBuilder(), result, entryArgs, resultAttrs,
177 SCModuleOp::getArgAttrsAttrName(result.name),
178 SCModuleOp::getResAttrsAttrName(result.name));
180 auto &body = *result.addRegion();
181 if (parser.parseRegion(body, entryArgs))
184 body.push_back(std::make_unique<Block>().release());
189void SCModuleOp::print(OpAsmPrinter &p) {
193 StringRef visibilityAttrName =
194 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
195 if (
auto visibility =
196 getOperation()->getAttrOfType<StringAttr>(visibilityAttrName))
197 p << visibility.getValue() <<
' ';
199 p.printSymbolName(SymbolTable::getSymbolName(*this).getValue());
202 bool needArgNamesAttr =
false;
204 p, *
this, getFunctionType().getInputs(),
false, {}, needArgNamesAttr);
205 mlir::function_interface_impl::printFunctionAttributes(
207 {
"portNames", getFunctionTypeAttrName(), getArgAttrsAttrName(),
208 getResAttrsAttrName()});
211 p.printRegion(getBody(),
false,
false);
215ArrayRef<Type> SCModuleOp::getArgumentTypes() {
216 return getFunctionType().getInputs();
220ArrayRef<Type> SCModuleOp::getResultTypes() {
221 return getFunctionType().getResults();
225 if (
auto inoutTy = dyn_cast<hw::InOutType>(type))
226 type = inoutTy.getElementType();
229 case hw::ModulePort::Direction::InOut:
230 return InOutType::get(type);
231 case hw::ModulePort::Direction::Input:
232 return InputType::get(type);
233 case hw::ModulePort::Direction::Output:
234 return OutputType::get(type);
236 llvm_unreachable(
"Impossible port direction");
239void SCModuleOp::build(OpBuilder &odsBuilder, OperationState &odsState,
240 StringAttr name, ArrayAttr portNames,
241 ArrayRef<Type> portTypes,
242 ArrayRef<NamedAttribute> attributes) {
243 odsState.addAttribute(getPortNamesAttrName(odsState.name), portNames);
244 Region *region = odsState.addRegion();
246 auto moduleType = odsBuilder.getFunctionType(portTypes, {});
247 odsState.addAttribute(getFunctionTypeAttrName(odsState.name),
248 TypeAttr::get(moduleType));
250 odsState.addAttribute(SCModuleOp::getSymNameAttrName(odsState.name), name);
251 region->push_back(
new Block);
252 region->addArguments(
254 SmallVector<Location>(portTypes.size(), odsBuilder.getUnknownLoc()));
255 odsState.addAttributes(attributes);
258void SCModuleOp::build(OpBuilder &odsBuilder, OperationState &odsState,
259 StringAttr name, ArrayRef<hw::PortInfo> ports,
260 ArrayRef<NamedAttribute> attributes) {
261 MLIRContext *ctxt = odsBuilder.getContext();
262 SmallVector<Attribute> portNames;
263 SmallVector<Type> portTypes;
264 for (
auto port : ports) {
265 portNames.push_back(StringAttr::get(ctxt, port.getName()));
268 build(odsBuilder, odsState, name, ArrayAttr::get(ctxt, portNames), portTypes);
271void SCModuleOp::build(OpBuilder &odsBuilder, OperationState &odsState,
273 ArrayRef<NamedAttribute> attributes) {
274 MLIRContext *ctxt = odsBuilder.getContext();
275 SmallVector<Attribute> portNames;
276 SmallVector<Type> portTypes;
277 for (
auto port : ports) {
278 portNames.push_back(StringAttr::get(ctxt, port.getName()));
281 build(odsBuilder, odsState, name, ArrayAttr::get(ctxt, portNames), portTypes);
284void SCModuleOp::getAsmBlockArgumentNames(mlir::Region ®ion,
289 ArrayAttr portNames = getPortNames();
290 for (
size_t i = 0, e = getNumArguments(); i != e; ++i) {
291 auto str = cast<StringAttr>(portNames[i]).getValue();
292 setNameFn(getArgument(i), str);
296LogicalResult SCModuleOp::verify() {
297 if (getFunctionType().getNumResults() != 0)
299 "incorrect number of function results (always has to be 0)");
300 if (getPortNames().size() != getFunctionType().getNumInputs())
301 return emitOpError(
"incorrect number of port names");
303 for (
auto arg : getArguments()) {
304 if (!hw::type_isa<InputType, OutputType, InOutType>(arg.getType()))
305 return mlir::emitError(
307 "module port must be of type 'sc_in', 'sc_out', or 'sc_inout'");
310 for (
auto portName : getPortNames()) {
311 if (cast<StringAttr>(portName).getValue().
empty())
312 return emitOpError(
"port name must not be empty");
318LogicalResult SCModuleOp::verifyRegions() {
319 auto attachNote = [&](mlir::InFlightDiagnostic &diag) {
320 diag.attachNote(
getLoc()) <<
"in module '@" << getModuleName() <<
"'";
325CtorOp SCModuleOp::getOrCreateCtor(OpBuilder &builder) {
327 getBody().walk([&](Operation *op) {
328 if ((ctor = dyn_cast<CtorOp>(op)))
329 return WalkResult::interrupt();
331 return WalkResult::skip();
337 OpBuilder::InsertionGuard guard(builder);
339 return CtorOp::create(builder,
getLoc());
342DestructorOp SCModuleOp::getOrCreateDestructor() {
343 DestructorOp destructor;
344 getBody().walk([&](Operation *op) {
345 if ((destructor = dyn_cast<DestructorOp>(op)))
346 return WalkResult::interrupt();
348 return WalkResult::skip();
355 return DestructorOp::create(builder,
getLoc());
362void SignalOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
363 setNameFn(getSignal(),
getName());
370OpFoldResult ConvertOp::fold(FoldAdaptor) {
371 if (getInput().getType() == getResult().getType())
374 if (
auto other = getInput().getDefiningOp<ConvertOp>()) {
375 Type inputType = other.getInput().getType();
376 Type intermediateType = getInput().getType();
378 if (inputType != getResult().getType())
383 bool inputSigned = isa<SignedType, IntBaseType>(inputType);
384 bool intermediateSigned = isa<SignedType, IntBaseType>(intermediateType);
385 if (inputSigned ^ intermediateSigned)
389 if (isa<LogicVectorBaseType, LogicType>(inputType) &&
390 !isa<LogicVectorBaseType, LogicType>(intermediateType))
394 auto intermediateBw =
getBitWidth(intermediateType);
396 if (!inputBw && intermediateBw) {
397 if (isa<IntBaseType, UIntBaseType>(inputType) && *intermediateBw >= 64)
398 return other.getInput();
403 if (!intermediateBw) {
404 if (isa<BitVectorBaseType, LogicVectorBaseType>(intermediateType))
405 return other.getInput();
407 if (!inputBw && isa<IntBaseType, UIntBaseType>(inputType) &&
408 isa<SignedType, UnsignedType>(intermediateType))
409 return other.getInput();
411 if (inputBw && *inputBw <= 64 &&
412 isa<IntBaseType, UIntBaseType, SignedType, UnsignedType>(
414 return other.getInput();
421 if (inputBw && intermediateBw && *inputBw <= *intermediateBw)
422 return other.getInput();
432LogicalResult CtorOp::verify() {
433 if (getBody().getNumArguments() != 0)
434 return emitOpError(
"must not have any arguments");
443void SCFuncOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
444 setNameFn(getHandle(),
getName());
447LogicalResult SCFuncOp::verify() {
448 if (getBody().getNumArguments() != 0)
449 return emitOpError(
"must not have any arguments");
458void InstanceDeclOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
459 setNameFn(getInstanceHandle(),
getName());
462StringRef InstanceDeclOp::getInstanceName() {
return getName(); }
463StringAttr InstanceDeclOp::getInstanceNameAttr() {
return getNameAttr(); }
468 if (
auto *result = cache->
getDefinition(getModuleNameAttr()))
471 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
472 return topLevelModuleOp.lookupSymbol(getModuleName());
476InstanceDeclOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
478 symbolTable.lookupNearestSymbolFrom(*this, getModuleNameAttr());
479 if (module ==
nullptr)
480 return emitError(
"cannot find module definition '")
481 << getModuleName() <<
"'";
483 auto emitError = [&](
const std::function<void(InFlightDiagnostic & diag)> &fn)
485 auto diag = emitOpError();
487 diag.attachNote(module->getLoc()) <<
"module declared here";
492 if (!isa<SCModuleOp>(module))
493 return emitError([&](
auto &diag) {
494 diag <<
"symbol reference '" << getModuleName()
495 <<
"' isn't a systemc module";
498 auto scModule = cast<SCModuleOp>(module);
501 if (scModule.getModuleName() != getInstanceType().getModuleName())
502 return emitError([&](
auto &diag) {
503 diag <<
"module names must match; expected '" << scModule.getModuleName()
504 <<
"' but got '" << getInstanceType().getModuleName().getValue()
509 ArrayRef<ModuleType::PortInfo> ports = getInstanceType().getPorts();
510 ArrayAttr modArgNames = scModule.getPortNames();
511 auto numPorts = ports.
size();
512 auto expectedPortTypes = scModule.getArgumentTypes();
514 if (expectedPortTypes.size() != numPorts)
515 return emitError([&](
auto &diag) {
516 diag <<
"has a wrong number of ports; expected "
517 << expectedPortTypes.size() <<
" but got " << numPorts;
520 for (
size_t i = 0; i != numPorts; ++i) {
521 if (ports[i].type != expectedPortTypes[i]) {
522 return emitError([&](
auto &diag) {
523 diag <<
"port type #" << i <<
" must be " << expectedPortTypes[i]
524 <<
", but got " << ports[i].type;
528 if (ports[i].name != modArgNames[i])
529 return emitError([&](
auto &diag) {
530 diag <<
"port name #" << i <<
" must be " << modArgNames[i]
531 <<
", but got " << ports[i].name;
538SmallVector<hw::PortInfo> InstanceDeclOp::getPortList() {
539 return cast<hw::PortList>(SymbolTable::lookupNearestSymbolFrom(
540 getOperation(), getReferencedModuleNameAttr()))
548LogicalResult DestructorOp::verify() {
549 if (getBody().getNumArguments() != 0)
550 return emitOpError(
"must not have any arguments");
559ParseResult BindPortOp::parse(OpAsmParser &parser, OperationState &result) {
560 OpAsmParser::UnresolvedOperand instance, channel;
561 std::string portName;
562 if (parser.parseOperand(instance) || parser.parseLSquare() ||
563 parser.parseString(&portName))
566 auto portNameLoc = parser.getCurrentLocation();
568 if (parser.parseRSquare() || parser.parseKeyword(
"to") ||
569 parser.parseOperand(channel))
572 if (parser.parseOptionalAttrDict(result.attributes))
575 auto typeListLoc = parser.getCurrentLocation();
576 SmallVector<Type> types;
577 if (parser.parseColonTypeList(types))
580 if (types.size() != 2)
581 return parser.emitError(typeListLoc,
582 "expected a list of exactly 2 types, but got ")
585 if (parser.resolveOperand(instance, types[0], result.operands))
587 if (parser.resolveOperand(channel, types[1], result.operands))
590 if (
auto moduleType = dyn_cast<ModuleType>(types[0])) {
591 auto ports = moduleType.getPorts();
593 for (
auto port : ports) {
594 if (port.name == portName)
598 if (index >= ports.size())
599 return parser.emitError(portNameLoc,
"port name \"")
600 << portName <<
"\" not found in module";
602 result.addAttribute(
"portId", parser.getBuilder().getIndexAttr(index));
610void BindPortOp::print(OpAsmPrinter &p) {
611 p <<
" " << getInstance() <<
"["
612 << cast<ModuleType>(getInstance().getType())
613 .getPorts()[getPortId().getZExtValue()]
615 <<
"] to " << getChannel();
616 p.printOptionalAttrDict((*this)->getAttrs(), {
"portId"});
617 p <<
" : " << getInstance().getType() <<
", " << getChannel().getType();
620LogicalResult BindPortOp::verify() {
621 auto ports = cast<ModuleType>(getInstance().getType()).getPorts();
622 if (getPortId().getZExtValue() >= ports.size())
623 return emitOpError(
"port #")
624 << getPortId().getZExtValue() <<
" does not exist, there are only "
625 << ports.size() <<
" ports";
628 Type portType = ports[getPortId().getZExtValue()].type;
629 Type channelType = getChannel().getType();
631 return emitOpError() << portType <<
" port cannot be bound to "
632 << channelType <<
" channel due to base type mismatch";
635 if ((isa<InputType>(portType) && isa<OutputType>(channelType)) ||
636 (isa<OutputType>(portType) && isa<InputType>(channelType)))
637 return emitOpError() << portType <<
" port cannot be bound to "
639 <<
" channel due to port direction mismatch";
644StringRef BindPortOp::getPortName() {
645 return cast<ModuleType>(getInstance().getType())
646 .getPorts()[getPortId().getZExtValue()]
654LogicalResult SensitiveOp::canonicalize(SensitiveOp op,
655 PatternRewriter &rewriter) {
656 if (op.getSensitivities().empty()) {
657 rewriter.eraseOp(op);
668void VariableOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
669 setNameFn(getVariable(),
getName());
672ParseResult VariableOp::parse(OpAsmParser &parser, OperationState &result) {
676 result.addAttribute(
"name", nameAttr);
678 OpAsmParser::UnresolvedOperand init;
679 auto initResult = parser.parseOptionalOperand(init);
681 if (parser.parseOptionalAttrDict(result.attributes))
685 if (parser.parseColonType(variableType))
688 if (initResult.has_value()) {
689 if (parser.resolveOperand(init, variableType, result.operands))
692 result.addTypes({variableType});
697void VariableOp::print(::mlir::OpAsmPrinter &p) {
701 p << getInit() <<
" ";
703 p.printOptionalAttrDict(getOperation()->getAttrs(), {
"name"});
704 p <<
": " << getVariable().getType();
707LogicalResult VariableOp::verify() {
708 if (getInit() && getInit().getType() != getVariable().getType())
710 "'init' and 'variable' must have the same type, but got ")
711 << getInit().getType() <<
" and " << getVariable().getType();
721void InteropVerilatedOp::build(OpBuilder &odsBuilder, OperationState &odsState,
722 Operation *module, StringAttr name,
723 ArrayRef<Value> inputs) {
724 auto mod = cast<hw::HWModuleLike>(module);
725 auto argNames = odsBuilder.getArrayAttr(mod.getInputNames());
726 auto resultNames = odsBuilder.getArrayAttr(mod.getOutputNames());
727 build(odsBuilder, odsState, mod.getHWModuleType().getOutputTypes(), name,
728 FlatSymbolRefAttr::get(SymbolTable::getSymbolName(module)), argNames,
729 resultNames, inputs);
733InteropVerilatedOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
735 *
this, getModuleNameAttr(), getInputs(), getResultTypes(),
736 getInputNames(), getResultNames(), ArrayAttr(), symbolTable);
741void InteropVerilatedOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
743 getResultNames(), getResults());
755LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
757 auto fnAttr = (*this)->getAttrOfType<FlatSymbolRefAttr>(
"callee");
759 return emitOpError(
"requires a 'callee' symbol reference attribute");
760 FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*
this, fnAttr);
762 return emitOpError() <<
"'" << fnAttr.getValue()
763 <<
"' does not reference a valid function";
766 auto fnType = fn.getFunctionType();
767 if (fnType.getNumInputs() != getNumOperands())
768 return emitOpError(
"incorrect number of operands for callee");
770 for (
unsigned i = 0, e = fnType.getNumInputs(); i != e; ++i)
771 if (getOperand(i).getType() != fnType.getInput(i))
772 return emitOpError(
"operand type mismatch: expected operand type ")
773 << fnType.getInput(i) <<
", but provided "
774 << getOperand(i).getType() <<
" for operand number " << i;
776 if (fnType.getNumResults() != getNumResults())
777 return emitOpError(
"incorrect number of results for callee");
779 for (
unsigned i = 0, e = fnType.getNumResults(); i != e; ++i)
780 if (getResult(i).getType() != fnType.getResult(i)) {
781 auto diag = emitOpError(
"result type mismatch at index ") << i;
782 diag.attachNote() <<
" op result types: " << getResultTypes();
783 diag.attachNote() <<
"function result types: " << fnType.getResults();
790FunctionType CallOp::getCalleeType() {
791 return FunctionType::get(getContext(), getOperandTypes(), getResultTypes());
795LogicalResult CallOp::verify() {
796 if (getNumResults() > 1)
798 "incorrect number of function results (always has to be 0 or 1)");
808LogicalResult CallIndirectOp::verify() {
809 if (getNumResults() > 1)
811 "incorrect number of function results (always has to be 0 or 1)");
826FuncOp FuncOp::create(Location location, StringRef name, ArrayAttr argNames,
827 FunctionType type, ArrayRef<NamedAttribute> attrs) {
828 OpBuilder builder(location->getContext());
829 OperationState state(location, getOperationName());
830 FuncOp::build(builder, state, name, argNames, type, attrs);
831 return cast<FuncOp>(Operation::create(state));
834FuncOp FuncOp::create(Location location, StringRef name, ArrayAttr argNames,
835 FunctionType type, Operation::dialect_attr_range attrs) {
836 SmallVector<NamedAttribute, 8> attrRef(attrs);
837 return create(location, name, argNames, type, ArrayRef(attrRef));
840FuncOp FuncOp::create(Location location, StringRef name, ArrayAttr argNames,
841 FunctionType type, ArrayRef<NamedAttribute> attrs,
842 ArrayRef<DictionaryAttr> argAttrs) {
843 FuncOp func = create(location, name, argNames, type, attrs);
844 func.setAllArgAttrs(argAttrs);
848void FuncOp::build(OpBuilder &odsBuilder, OperationState &odsState,
849 StringRef name, ArrayAttr argNames, FunctionType type,
850 ArrayRef<NamedAttribute> attrs,
851 ArrayRef<DictionaryAttr> argAttrs) {
852 odsState.addAttribute(getArgNamesAttrName(odsState.name), argNames);
853 odsState.addAttribute(FuncOp::getSymNameAttrName(odsState.name),
854 odsBuilder.getStringAttr(name));
855 odsState.addAttribute(FuncOp::getFunctionTypeAttrName(odsState.name),
856 TypeAttr::get(type));
857 odsState.attributes.append(attrs.begin(), attrs.end());
858 odsState.addRegion();
860 if (argAttrs.empty())
862 assert(type.getNumInputs() == argAttrs.size());
863 mlir::call_interface_impl::addArgAndResultAttrs(
864 odsBuilder, odsState, argAttrs,
865 {}, FuncOp::getArgAttrsAttrName(odsState.name),
866 FuncOp::getResAttrsAttrName(odsState.name));
869ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
871 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
872 mlir::function_interface_impl::VariadicFlag,
873 std::string &) {
return builder.getFunctionType(argTypes, results); };
877 if (succeeded(parser.parseOptionalKeyword(
"externC")))
878 result.addAttribute(getExternCAttrName(result.name),
879 UnitAttr::get(result.getContext()));
884 SmallVector<OpAsmParser::Argument> entryArgs;
885 SmallVector<DictionaryAttr> resultAttrs;
886 SmallVector<Type> resultTypes;
887 auto &builder = parser.getBuilder();
890 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
894 if (parser.parseSymbolName(nameAttr, FuncOp::getSymNameAttrName(result.name),
899 mlir::SMLoc signatureLocation = parser.getCurrentLocation();
900 bool isVariadic =
false;
901 if (mlir::function_interface_impl::parseFunctionSignatureWithArguments(
902 parser,
false, entryArgs, isVariadic, resultTypes, resultAttrs))
905 std::string errorMessage;
906 SmallVector<Type> argTypes;
907 argTypes.reserve(entryArgs.size());
908 for (
auto &arg : entryArgs)
909 argTypes.push_back(arg.type);
911 Type type = buildFuncType(
912 builder, argTypes, resultTypes,
913 mlir::function_interface_impl::VariadicFlag(isVariadic), errorMessage);
915 return parser.emitError(signatureLocation)
916 <<
"failed to construct function type"
917 << (errorMessage.empty() ?
"" :
": ") << errorMessage;
919 result.addAttribute(FuncOp::getFunctionTypeAttrName(result.name),
920 TypeAttr::get(type));
923 NamedAttrList parsedAttributes;
924 mlir::SMLoc attributeDictLocation = parser.getCurrentLocation();
925 if (parser.parseOptionalAttrDictWithKeyword(parsedAttributes))
930 for (StringRef disallowed :
931 {mlir::SymbolOpInterface::getDefaultVisibilityAttrName(),
932 FuncOp::getSymNameAttrName(result.name).getValue(),
933 FuncOp::getFunctionTypeAttrName(result.name).getValue()}) {
934 if (parsedAttributes.get(disallowed))
935 return parser.emitError(attributeDictLocation,
"'")
937 <<
"' is an inferred attribute and should not be specified in the "
938 "explicit attribute dictionary";
940 result.attributes.append(parsedAttributes);
943 assert(resultAttrs.size() == resultTypes.size());
944 mlir::call_interface_impl::addArgAndResultAttrs(
945 builder, result, entryArgs, resultAttrs,
946 FuncOp::getArgAttrsAttrName(result.name),
947 FuncOp::getResAttrsAttrName(result.name));
951 auto *body = result.addRegion();
952 mlir::SMLoc loc = parser.getCurrentLocation();
953 mlir::OptionalParseResult parseResult =
954 parser.parseOptionalRegion(*body, entryArgs,
956 if (parseResult.has_value()) {
957 if (failed(*parseResult))
961 return parser.emitError(loc,
"expected non-empty function body");
966 SmallVector<Attribute> argNames;
967 if (!entryArgs.empty() && !entryArgs.front().ssaName.name.empty()) {
968 for (
auto &arg : entryArgs)
970 StringAttr::
get(parser.getContext(), arg.ssaName.name.drop_front()));
973 result.addAttribute(getArgNamesAttrName(result.name),
974 ArrayAttr::get(parser.getContext(), argNames));
979void FuncOp::print(OpAsmPrinter &p) {
983 mlir::FunctionOpInterface op = *
this;
989 auto funcName = cast<mlir::SymbolOpInterface>(op.getOperation()).getName();
992 StringRef visibilityAttrName =
993 mlir::SymbolOpInterface::getDefaultVisibilityAttrName();
994 if (
auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
995 p << visibility.getValue() <<
' ';
996 p.printSymbolName(funcName);
998 ArrayRef<Type> argTypes = op.getArgumentTypes();
999 ArrayRef<Type> resultTypes = op.getResultTypes();
1000 mlir::function_interface_impl::printFunctionSignature(p, op, argTypes,
false,
1002 mlir::function_interface_impl::printFunctionAttributes(
1004 {visibilityAttrName,
"externC",
"argNames", getFunctionTypeAttrName(),
1005 getArgAttrsAttrName(), getResAttrsAttrName()});
1007 Region &body = op->getRegion(0);
1008 if (!body.empty()) {
1010 p.printRegion(body,
false,
1019void FuncOp::cloneInto(FuncOp dest, IRMapping &mapper) {
1022 for (
const auto &attr : dest->getAttrs())
1023 newAttrMap.insert({attr.getName(), attr.getValue()});
1024 for (
const auto &attr : (*this)->getAttrs())
1025 newAttrMap.insert({attr.getName(), attr.getValue()});
1027 auto newAttrs = llvm::to_vector(llvm::map_range(
1028 newAttrMap, [](std::pair<StringAttr, Attribute> attrPair) {
1029 return NamedAttribute(attrPair.first, attrPair.second);
1031 dest->setAttrs(DictionaryAttr::get(getContext(), newAttrs));
1034 getBody().cloneInto(&dest.getBody(), mapper);
1042FuncOp FuncOp::clone(IRMapping &mapper) {
1044 FuncOp newFunc = cast<FuncOp>(getOperation()->cloneWithoutRegions());
1049 if (!isExternal()) {
1050 FunctionType oldType = getFunctionType();
1052 unsigned oldNumArgs = oldType.getNumInputs();
1053 SmallVector<Type, 4> newInputs;
1054 newInputs.reserve(oldNumArgs);
1055 for (
unsigned i = 0; i != oldNumArgs; ++i)
1056 if (!mapper.contains(getArgument(i)))
1057 newInputs.push_back(oldType.getInput(i));
1061 if (newInputs.size() != oldNumArgs) {
1062 newFunc.setType(FunctionType::get(oldType.getContext(), newInputs,
1063 oldType.getResults()));
1065 if (ArrayAttr argAttrs = getAllArgAttrs()) {
1066 SmallVector<Attribute> newArgAttrs;
1067 newArgAttrs.reserve(newInputs.size());
1068 for (
unsigned i = 0; i != oldNumArgs; ++i)
1069 if (!mapper.contains(getArgument(i)))
1070 newArgAttrs.push_back(argAttrs[i]);
1071 newFunc.setAllArgAttrs(newArgAttrs);
1077 cloneInto(newFunc, mapper);
1081FuncOp FuncOp::clone() {
1083 return clone(mapper);
1088void FuncOp::getAsmBlockArgumentNames(mlir::Region ®ion,
1093 for (
auto [arg, name] :
llvm::zip(getArguments(), getArgNames()))
1094 setNameFn(arg, cast<StringAttr>(name).getValue());
1097LogicalResult FuncOp::verify() {
1098 if (getFunctionType().getNumResults() > 1)
1100 "incorrect number of function results (always has to be 0 or 1)");
1102 if (getBody().
empty())
1105 if (getArgNames().size() != getFunctionType().getNumInputs())
1106 return emitOpError(
"incorrect number of argument names");
1108 for (
auto portName : getArgNames()) {
1109 if (cast<StringAttr>(portName).getValue().
empty())
1110 return emitOpError(
"arg name must not be empty");
1116LogicalResult FuncOp::verifyRegions() {
1117 auto attachNote = [&](mlir::InFlightDiagnostic &diag) {
1118 diag.attachNote(
getLoc()) <<
"in function '@" <<
getName() <<
"'";
1131LogicalResult ReturnOp::verify() {
1132 auto function = cast<FuncOp>((*this)->getParentOp());
1135 const auto &results = function.getFunctionType().getResults();
1136 if (getNumOperands() != results.size())
1137 return emitOpError(
"has ")
1138 << getNumOperands() <<
" operands, but enclosing function (@"
1139 << function.getName() <<
") returns " << results.size();
1141 for (
unsigned i = 0, e = results.size(); i != e; ++i)
1142 if (getOperand(i).getType() != results[i])
1143 return emitError() <<
"type of return operand " << i <<
" ("
1144 << getOperand(i).getType()
1145 <<
") doesn't match function result type ("
1146 << results[i] <<
")"
1147 <<
" in function @" << function.getName();
1157#define GET_OP_CLASSES
1158#include "circt/Dialect/SystemC/SystemC.cpp.inc"
assert(baseType &&"element must be base type")
static Location getLoc(DefSlot slot)
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
static hw::ModulePort::Direction getDirection(Type type)
static Type wrapPortType(Type type, hw::ModulePort::Direction direction)
static LogicalResult verifyUniqueNamesInRegion(Operation *operation, ArrayAttr argNames, std::function< void(mlir::InFlightDiagnostic &)> attachNote)
This stores lookup tables to make manipulating and working with the IR more efficient.
mlir::Operation * getDefinition(mlir::Attribute attr) const override
Lookup a definition for 'symbol' in the cache.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
std::string getInstanceName(mlir::func::CallOp callOp)
A helper function to get the instance name.
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.
void printModuleSignature(OpAsmPrinter &p, Operation *op, ArrayRef< Type > argTypes, bool isVariadic, ArrayRef< Type > resultTypes, bool &needArgNamesAttr)
Print a module signature with named results.
ParseResult parseModuleFunctionSignature(OpAsmParser &parser, bool &isVariadic, SmallVectorImpl< OpAsmParser::Argument > &args, SmallVectorImpl< Attribute > &argNames, SmallVectorImpl< Attribute > &argLocs, SmallVectorImpl< Attribute > &resultNames, SmallVectorImpl< DictionaryAttr > &resultAttrs, SmallVectorImpl< Attribute > &resultLocs, TypeAttr &type)
This is a variant of mlir::parseFunctionSignature that allows names on result arguments.
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Type getSignalBaseType(Type type)
Get the type wrapped by a signal or port (in, inout, out) type.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
ParseResult parseImplicitSSAName(OpAsmParser &parser, StringAttr &attr)
Parse an implicit SSA name string attribute.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
This holds a decoded list of input/inout and output ports for a module or instance.
This holds the name, type, direction of a module's ports.