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() {
139 ->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
143ParseResult SCModuleOp::parse(OpAsmParser &parser, OperationState &result) {
146 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
149 StringAttr moduleName;
150 if (parser.parseSymbolName(moduleName, SymbolTable::getSymbolAttrName(),
155 bool isVariadic =
false;
156 SmallVector<OpAsmParser::Argument, 4> entryArgs;
157 SmallVector<Attribute> argNames;
158 SmallVector<Attribute> argLocs;
159 SmallVector<Attribute> resultNames;
160 SmallVector<DictionaryAttr> resultAttrs;
161 SmallVector<Attribute> resultLocs;
162 TypeAttr functionType;
164 parser, isVariadic, entryArgs, argNames, argLocs, resultNames,
165 resultAttrs, resultLocs, functionType)))
169 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
172 result.addAttribute(
"portNames",
173 ArrayAttr::get(parser.getContext(), argNames));
175 result.addAttribute(SCModuleOp::getFunctionTypeAttrName(result.name),
178 mlir::call_interface_impl::addArgAndResultAttrs(
179 parser.getBuilder(), result, entryArgs, resultAttrs,
180 SCModuleOp::getArgAttrsAttrName(result.name),
181 SCModuleOp::getResAttrsAttrName(result.name));
183 auto &body = *result.addRegion();
184 if (parser.parseRegion(body, entryArgs))
187 body.push_back(std::make_unique<Block>().release());
192void SCModuleOp::print(OpAsmPrinter &p) {
196 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
197 if (
auto visibility =
198 getOperation()->getAttrOfType<StringAttr>(visibilityAttrName))
199 p << visibility.getValue() <<
' ';
201 p.printSymbolName(SymbolTable::getSymbolName(*this).getValue());
204 bool needArgNamesAttr =
false;
206 p, *
this, getFunctionType().getInputs(),
false, {}, needArgNamesAttr);
207 mlir::function_interface_impl::printFunctionAttributes(
209 {
"portNames", getFunctionTypeAttrName(), getArgAttrsAttrName(),
210 getResAttrsAttrName()});
213 p.printRegion(getBody(),
false,
false);
217ArrayRef<Type> SCModuleOp::getArgumentTypes() {
218 return getFunctionType().getInputs();
222ArrayRef<Type> SCModuleOp::getResultTypes() {
223 return getFunctionType().getResults();
227 if (
auto inoutTy = dyn_cast<hw::InOutType>(type))
228 type = inoutTy.getElementType();
231 case hw::ModulePort::Direction::InOut:
232 return InOutType::get(type);
233 case hw::ModulePort::Direction::Input:
234 return InputType::get(type);
235 case hw::ModulePort::Direction::Output:
236 return OutputType::get(type);
238 llvm_unreachable(
"Impossible port direction");
241void SCModuleOp::build(OpBuilder &odsBuilder, OperationState &odsState,
242 StringAttr name, ArrayAttr portNames,
243 ArrayRef<Type> portTypes,
244 ArrayRef<NamedAttribute> attributes) {
245 odsState.addAttribute(getPortNamesAttrName(odsState.name), portNames);
246 Region *region = odsState.addRegion();
248 auto moduleType = odsBuilder.getFunctionType(portTypes, {});
249 odsState.addAttribute(getFunctionTypeAttrName(odsState.name),
250 TypeAttr::get(moduleType));
252 odsState.addAttribute(SymbolTable::getSymbolAttrName(), name);
253 region->push_back(
new Block);
254 region->addArguments(
256 SmallVector<Location>(portTypes.size(), odsBuilder.getUnknownLoc()));
257 odsState.addAttributes(attributes);
260void SCModuleOp::build(OpBuilder &odsBuilder, OperationState &odsState,
261 StringAttr name, ArrayRef<hw::PortInfo> ports,
262 ArrayRef<NamedAttribute> attributes) {
263 MLIRContext *ctxt = odsBuilder.getContext();
264 SmallVector<Attribute> portNames;
265 SmallVector<Type> portTypes;
266 for (
auto port : ports) {
267 portNames.push_back(StringAttr::get(ctxt, port.getName()));
270 build(odsBuilder, odsState, name, ArrayAttr::get(ctxt, portNames), portTypes);
273void SCModuleOp::build(OpBuilder &odsBuilder, OperationState &odsState,
275 ArrayRef<NamedAttribute> attributes) {
276 MLIRContext *ctxt = odsBuilder.getContext();
277 SmallVector<Attribute> portNames;
278 SmallVector<Type> portTypes;
279 for (
auto port : ports) {
280 portNames.push_back(StringAttr::get(ctxt, port.getName()));
283 build(odsBuilder, odsState, name, ArrayAttr::get(ctxt, portNames), portTypes);
286void SCModuleOp::getAsmBlockArgumentNames(mlir::Region ®ion,
291 ArrayAttr portNames = getPortNames();
292 for (
size_t i = 0, e = getNumArguments(); i != e; ++i) {
293 auto str = cast<StringAttr>(portNames[i]).getValue();
294 setNameFn(getArgument(i), str);
298LogicalResult SCModuleOp::verify() {
299 if (getFunctionType().getNumResults() != 0)
301 "incorrect number of function results (always has to be 0)");
302 if (getPortNames().size() != getFunctionType().getNumInputs())
303 return emitOpError(
"incorrect number of port names");
305 for (
auto arg : getArguments()) {
306 if (!hw::type_isa<InputType, OutputType, InOutType>(arg.getType()))
307 return mlir::emitError(
309 "module port must be of type 'sc_in', 'sc_out', or 'sc_inout'");
312 for (
auto portName : getPortNames()) {
313 if (cast<StringAttr>(portName).getValue().
empty())
314 return emitOpError(
"port name must not be empty");
320LogicalResult SCModuleOp::verifyRegions() {
321 auto attachNote = [&](mlir::InFlightDiagnostic &diag) {
322 diag.attachNote(
getLoc()) <<
"in module '@" << getModuleName() <<
"'";
327CtorOp SCModuleOp::getOrCreateCtor(OpBuilder &builder) {
329 getBody().walk([&](Operation *op) {
330 if ((ctor = dyn_cast<CtorOp>(op)))
331 return WalkResult::interrupt();
333 return WalkResult::skip();
339 OpBuilder::InsertionGuard guard(builder);
341 return CtorOp::create(builder,
getLoc());
344DestructorOp SCModuleOp::getOrCreateDestructor() {
345 DestructorOp destructor;
346 getBody().walk([&](Operation *op) {
347 if ((destructor = dyn_cast<DestructorOp>(op)))
348 return WalkResult::interrupt();
350 return WalkResult::skip();
357 return DestructorOp::create(builder,
getLoc());
364void SignalOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
365 setNameFn(getSignal(),
getName());
372OpFoldResult ConvertOp::fold(FoldAdaptor) {
373 if (getInput().getType() == getResult().getType())
376 if (
auto other = getInput().getDefiningOp<ConvertOp>()) {
377 Type inputType = other.getInput().getType();
378 Type intermediateType = getInput().getType();
380 if (inputType != getResult().getType())
385 bool inputSigned = isa<SignedType, IntBaseType>(inputType);
386 bool intermediateSigned = isa<SignedType, IntBaseType>(intermediateType);
387 if (inputSigned ^ intermediateSigned)
391 if (isa<LogicVectorBaseType, LogicType>(inputType) &&
392 !isa<LogicVectorBaseType, LogicType>(intermediateType))
396 auto intermediateBw =
getBitWidth(intermediateType);
398 if (!inputBw && intermediateBw) {
399 if (isa<IntBaseType, UIntBaseType>(inputType) && *intermediateBw >= 64)
400 return other.getInput();
405 if (!intermediateBw) {
406 if (isa<BitVectorBaseType, LogicVectorBaseType>(intermediateType))
407 return other.getInput();
409 if (!inputBw && isa<IntBaseType, UIntBaseType>(inputType) &&
410 isa<SignedType, UnsignedType>(intermediateType))
411 return other.getInput();
413 if (inputBw && *inputBw <= 64 &&
414 isa<IntBaseType, UIntBaseType, SignedType, UnsignedType>(
416 return other.getInput();
423 if (inputBw && intermediateBw && *inputBw <= *intermediateBw)
424 return other.getInput();
434LogicalResult CtorOp::verify() {
435 if (getBody().getNumArguments() != 0)
436 return emitOpError(
"must not have any arguments");
445void SCFuncOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
446 setNameFn(getHandle(),
getName());
449LogicalResult SCFuncOp::verify() {
450 if (getBody().getNumArguments() != 0)
451 return emitOpError(
"must not have any arguments");
460void InstanceDeclOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
461 setNameFn(getInstanceHandle(),
getName());
464StringRef InstanceDeclOp::getInstanceName() {
return getName(); }
465StringAttr InstanceDeclOp::getInstanceNameAttr() {
return getNameAttr(); }
470 if (
auto *result = cache->
getDefinition(getModuleNameAttr()))
473 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
474 return topLevelModuleOp.lookupSymbol(getModuleName());
478InstanceDeclOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
480 symbolTable.lookupNearestSymbolFrom(*this, getModuleNameAttr());
481 if (module ==
nullptr)
482 return emitError(
"cannot find module definition '")
483 << getModuleName() <<
"'";
485 auto emitError = [&](
const std::function<void(InFlightDiagnostic & diag)> &fn)
487 auto diag = emitOpError();
489 diag.attachNote(module->getLoc()) <<
"module declared here";
494 if (!isa<SCModuleOp>(module))
495 return emitError([&](
auto &diag) {
496 diag <<
"symbol reference '" << getModuleName()
497 <<
"' isn't a systemc module";
500 auto scModule = cast<SCModuleOp>(module);
503 if (scModule.getModuleName() != getInstanceType().getModuleName())
504 return emitError([&](
auto &diag) {
505 diag <<
"module names must match; expected '" << scModule.getModuleName()
506 <<
"' but got '" << getInstanceType().getModuleName().getValue()
511 ArrayRef<ModuleType::PortInfo> ports = getInstanceType().getPorts();
512 ArrayAttr modArgNames = scModule.getPortNames();
513 auto numPorts = ports.
size();
514 auto expectedPortTypes = scModule.getArgumentTypes();
516 if (expectedPortTypes.size() != numPorts)
517 return emitError([&](
auto &diag) {
518 diag <<
"has a wrong number of ports; expected "
519 << expectedPortTypes.size() <<
" but got " << numPorts;
522 for (
size_t i = 0; i != numPorts; ++i) {
523 if (ports[i].type != expectedPortTypes[i]) {
524 return emitError([&](
auto &diag) {
525 diag <<
"port type #" << i <<
" must be " << expectedPortTypes[i]
526 <<
", but got " << ports[i].type;
530 if (ports[i].name != modArgNames[i])
531 return emitError([&](
auto &diag) {
532 diag <<
"port name #" << i <<
" must be " << modArgNames[i]
533 <<
", but got " << ports[i].name;
540SmallVector<hw::PortInfo> InstanceDeclOp::getPortList() {
541 return cast<hw::PortList>(SymbolTable::lookupNearestSymbolFrom(
542 getOperation(), getReferencedModuleNameAttr()))
550LogicalResult DestructorOp::verify() {
551 if (getBody().getNumArguments() != 0)
552 return emitOpError(
"must not have any arguments");
561ParseResult BindPortOp::parse(OpAsmParser &parser, OperationState &result) {
562 OpAsmParser::UnresolvedOperand instance, channel;
563 std::string portName;
564 if (parser.parseOperand(instance) || parser.parseLSquare() ||
565 parser.parseString(&portName))
568 auto portNameLoc = parser.getCurrentLocation();
570 if (parser.parseRSquare() || parser.parseKeyword(
"to") ||
571 parser.parseOperand(channel))
574 if (parser.parseOptionalAttrDict(result.attributes))
577 auto typeListLoc = parser.getCurrentLocation();
578 SmallVector<Type> types;
579 if (parser.parseColonTypeList(types))
582 if (types.size() != 2)
583 return parser.emitError(typeListLoc,
584 "expected a list of exactly 2 types, but got ")
587 if (parser.resolveOperand(instance, types[0], result.operands))
589 if (parser.resolveOperand(channel, types[1], result.operands))
592 if (
auto moduleType = dyn_cast<ModuleType>(types[0])) {
593 auto ports = moduleType.getPorts();
595 for (
auto port : ports) {
596 if (port.name == portName)
600 if (index >= ports.size())
601 return parser.emitError(portNameLoc,
"port name \"")
602 << portName <<
"\" not found in module";
604 result.addAttribute(
"portId", parser.getBuilder().getIndexAttr(index));
612void BindPortOp::print(OpAsmPrinter &p) {
613 p <<
" " << getInstance() <<
"["
614 << cast<ModuleType>(getInstance().getType())
615 .getPorts()[getPortId().getZExtValue()]
617 <<
"] to " << getChannel();
618 p.printOptionalAttrDict((*this)->getAttrs(), {
"portId"});
619 p <<
" : " << getInstance().getType() <<
", " << getChannel().getType();
622LogicalResult BindPortOp::verify() {
623 auto ports = cast<ModuleType>(getInstance().getType()).getPorts();
624 if (getPortId().getZExtValue() >= ports.size())
625 return emitOpError(
"port #")
626 << getPortId().getZExtValue() <<
" does not exist, there are only "
627 << ports.size() <<
" ports";
630 Type portType = ports[getPortId().getZExtValue()].type;
631 Type channelType = getChannel().getType();
633 return emitOpError() << portType <<
" port cannot be bound to "
634 << channelType <<
" channel due to base type mismatch";
637 if ((isa<InputType>(portType) && isa<OutputType>(channelType)) ||
638 (isa<OutputType>(portType) && isa<InputType>(channelType)))
639 return emitOpError() << portType <<
" port cannot be bound to "
641 <<
" channel due to port direction mismatch";
646StringRef BindPortOp::getPortName() {
647 return cast<ModuleType>(getInstance().getType())
648 .getPorts()[getPortId().getZExtValue()]
656LogicalResult SensitiveOp::canonicalize(SensitiveOp op,
657 PatternRewriter &rewriter) {
658 if (op.getSensitivities().empty()) {
659 rewriter.eraseOp(op);
670void VariableOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
671 setNameFn(getVariable(),
getName());
674ParseResult VariableOp::parse(OpAsmParser &parser, OperationState &result) {
678 result.addAttribute(
"name", nameAttr);
680 OpAsmParser::UnresolvedOperand init;
681 auto initResult = parser.parseOptionalOperand(init);
683 if (parser.parseOptionalAttrDict(result.attributes))
687 if (parser.parseColonType(variableType))
690 if (initResult.has_value()) {
691 if (parser.resolveOperand(init, variableType, result.operands))
694 result.addTypes({variableType});
699void VariableOp::print(::mlir::OpAsmPrinter &p) {
703 p << getInit() <<
" ";
705 p.printOptionalAttrDict(getOperation()->getAttrs(), {
"name"});
706 p <<
": " << getVariable().getType();
709LogicalResult VariableOp::verify() {
710 if (getInit() && getInit().getType() != getVariable().getType())
712 "'init' and 'variable' must have the same type, but got ")
713 << getInit().getType() <<
" and " << getVariable().getType();
723void InteropVerilatedOp::build(OpBuilder &odsBuilder, OperationState &odsState,
724 Operation *module, StringAttr name,
725 ArrayRef<Value> inputs) {
726 auto mod = cast<hw::HWModuleLike>(module);
727 auto argNames = odsBuilder.getArrayAttr(mod.getInputNames());
728 auto resultNames = odsBuilder.getArrayAttr(mod.getOutputNames());
729 build(odsBuilder, odsState, mod.getHWModuleType().getOutputTypes(), name,
730 FlatSymbolRefAttr::get(SymbolTable::getSymbolName(module)), argNames,
731 resultNames, inputs);
735InteropVerilatedOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
737 *
this, getModuleNameAttr(), getInputs(), getResultTypes(),
738 getInputNames(), getResultNames(), ArrayAttr(), symbolTable);
743void InteropVerilatedOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
745 getResultNames(), getResults());
757LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
759 auto fnAttr = (*this)->getAttrOfType<FlatSymbolRefAttr>(
"callee");
761 return emitOpError(
"requires a 'callee' symbol reference attribute");
762 FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*
this, fnAttr);
764 return emitOpError() <<
"'" << fnAttr.getValue()
765 <<
"' does not reference a valid function";
768 auto fnType = fn.getFunctionType();
769 if (fnType.getNumInputs() != getNumOperands())
770 return emitOpError(
"incorrect number of operands for callee");
772 for (
unsigned i = 0, e = fnType.getNumInputs(); i != e; ++i)
773 if (getOperand(i).getType() != fnType.getInput(i))
774 return emitOpError(
"operand type mismatch: expected operand type ")
775 << fnType.getInput(i) <<
", but provided "
776 << getOperand(i).getType() <<
" for operand number " << i;
778 if (fnType.getNumResults() != getNumResults())
779 return emitOpError(
"incorrect number of results for callee");
781 for (
unsigned i = 0, e = fnType.getNumResults(); i != e; ++i)
782 if (getResult(i).getType() != fnType.getResult(i)) {
783 auto diag = emitOpError(
"result type mismatch at index ") << i;
784 diag.attachNote() <<
" op result types: " << getResultTypes();
785 diag.attachNote() <<
"function result types: " << fnType.getResults();
792FunctionType CallOp::getCalleeType() {
793 return FunctionType::get(getContext(), getOperandTypes(), getResultTypes());
797LogicalResult CallOp::verify() {
798 if (getNumResults() > 1)
800 "incorrect number of function results (always has to be 0 or 1)");
810LogicalResult CallIndirectOp::verify() {
811 if (getNumResults() > 1)
813 "incorrect number of function results (always has to be 0 or 1)");
828FuncOp FuncOp::create(Location location, StringRef name, ArrayAttr argNames,
829 FunctionType type, ArrayRef<NamedAttribute> attrs) {
830 OpBuilder builder(location->getContext());
831 OperationState state(location, getOperationName());
832 FuncOp::build(builder, state, name, argNames, type, attrs);
833 return cast<FuncOp>(Operation::create(state));
836FuncOp FuncOp::create(Location location, StringRef name, ArrayAttr argNames,
837 FunctionType type, Operation::dialect_attr_range attrs) {
838 SmallVector<NamedAttribute, 8> attrRef(attrs);
839 return create(location, name, argNames, type, ArrayRef(attrRef));
842FuncOp FuncOp::create(Location location, StringRef name, ArrayAttr argNames,
843 FunctionType type, ArrayRef<NamedAttribute> attrs,
844 ArrayRef<DictionaryAttr> argAttrs) {
845 FuncOp func = create(location, name, argNames, type, attrs);
846 func.setAllArgAttrs(argAttrs);
850void FuncOp::build(OpBuilder &odsBuilder, OperationState &odsState,
851 StringRef name, ArrayAttr argNames, FunctionType type,
852 ArrayRef<NamedAttribute> attrs,
853 ArrayRef<DictionaryAttr> argAttrs) {
854 odsState.addAttribute(getArgNamesAttrName(odsState.name), argNames);
855 odsState.addAttribute(SymbolTable::getSymbolAttrName(),
856 odsBuilder.getStringAttr(name));
857 odsState.addAttribute(FuncOp::getFunctionTypeAttrName(odsState.name),
858 TypeAttr::get(type));
859 odsState.attributes.append(attrs.begin(), attrs.end());
860 odsState.addRegion();
862 if (argAttrs.empty())
864 assert(type.getNumInputs() == argAttrs.size());
865 mlir::call_interface_impl::addArgAndResultAttrs(
866 odsBuilder, odsState, argAttrs,
867 {}, FuncOp::getArgAttrsAttrName(odsState.name),
868 FuncOp::getResAttrsAttrName(odsState.name));
871ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
873 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
874 mlir::function_interface_impl::VariadicFlag,
875 std::string &) {
return builder.getFunctionType(argTypes, results); };
879 if (succeeded(parser.parseOptionalKeyword(
"externC")))
880 result.addAttribute(getExternCAttrName(result.name),
881 UnitAttr::get(result.getContext()));
886 SmallVector<OpAsmParser::Argument> entryArgs;
887 SmallVector<DictionaryAttr> resultAttrs;
888 SmallVector<Type> resultTypes;
889 auto &builder = parser.getBuilder();
892 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
896 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
901 mlir::SMLoc signatureLocation = parser.getCurrentLocation();
902 bool isVariadic =
false;
903 if (mlir::function_interface_impl::parseFunctionSignatureWithArguments(
904 parser,
false, entryArgs, isVariadic, resultTypes, resultAttrs))
907 std::string errorMessage;
908 SmallVector<Type> argTypes;
909 argTypes.reserve(entryArgs.size());
910 for (
auto &arg : entryArgs)
911 argTypes.push_back(arg.type);
913 Type type = buildFuncType(
914 builder, argTypes, resultTypes,
915 mlir::function_interface_impl::VariadicFlag(isVariadic), errorMessage);
917 return parser.emitError(signatureLocation)
918 <<
"failed to construct function type"
919 << (errorMessage.empty() ?
"" :
": ") << errorMessage;
921 result.addAttribute(FuncOp::getFunctionTypeAttrName(result.name),
922 TypeAttr::get(type));
925 NamedAttrList parsedAttributes;
926 mlir::SMLoc attributeDictLocation = parser.getCurrentLocation();
927 if (parser.parseOptionalAttrDictWithKeyword(parsedAttributes))
932 for (StringRef disallowed :
933 {SymbolTable::getVisibilityAttrName(), SymbolTable::getSymbolAttrName(),
934 FuncOp::getFunctionTypeAttrName(result.name).getValue()}) {
935 if (parsedAttributes.get(disallowed))
936 return parser.emitError(attributeDictLocation,
"'")
938 <<
"' is an inferred attribute and should not be specified in the "
939 "explicit attribute dictionary";
941 result.attributes.append(parsedAttributes);
944 assert(resultAttrs.size() == resultTypes.size());
945 mlir::call_interface_impl::addArgAndResultAttrs(
946 builder, result, entryArgs, resultAttrs,
947 FuncOp::getArgAttrsAttrName(result.name),
948 FuncOp::getResAttrsAttrName(result.name));
952 auto *body = result.addRegion();
953 mlir::SMLoc loc = parser.getCurrentLocation();
954 mlir::OptionalParseResult parseResult =
955 parser.parseOptionalRegion(*body, entryArgs,
957 if (parseResult.has_value()) {
958 if (failed(*parseResult))
962 return parser.emitError(loc,
"expected non-empty function body");
967 SmallVector<Attribute> argNames;
968 if (!entryArgs.empty() && !entryArgs.front().ssaName.name.empty()) {
969 for (
auto &arg : entryArgs)
971 StringAttr::
get(parser.getContext(), arg.ssaName.name.drop_front()));
974 result.addAttribute(getArgNamesAttrName(result.name),
975 ArrayAttr::get(parser.getContext(), argNames));
980void FuncOp::print(OpAsmPrinter &p) {
984 mlir::FunctionOpInterface op = *
this;
991 op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
995 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
996 if (
auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
997 p << visibility.getValue() <<
' ';
998 p.printSymbolName(funcName);
1000 ArrayRef<Type> argTypes = op.getArgumentTypes();
1001 ArrayRef<Type> resultTypes = op.getResultTypes();
1002 mlir::function_interface_impl::printFunctionSignature(p, op, argTypes,
false,
1004 mlir::function_interface_impl::printFunctionAttributes(
1006 {visibilityAttrName,
"externC",
"argNames", getFunctionTypeAttrName(),
1007 getArgAttrsAttrName(), getResAttrsAttrName()});
1009 Region &body = op->getRegion(0);
1010 if (!body.empty()) {
1012 p.printRegion(body,
false,
1021void FuncOp::cloneInto(FuncOp dest, IRMapping &mapper) {
1024 for (
const auto &attr : dest->getAttrs())
1025 newAttrMap.insert({attr.getName(), attr.getValue()});
1026 for (
const auto &attr : (*this)->getAttrs())
1027 newAttrMap.insert({attr.getName(), attr.getValue()});
1029 auto newAttrs = llvm::to_vector(llvm::map_range(
1030 newAttrMap, [](std::pair<StringAttr, Attribute> attrPair) {
1031 return NamedAttribute(attrPair.first, attrPair.second);
1033 dest->setAttrs(DictionaryAttr::get(getContext(), newAttrs));
1036 getBody().cloneInto(&dest.getBody(), mapper);
1044FuncOp FuncOp::clone(IRMapping &mapper) {
1046 FuncOp newFunc = cast<FuncOp>(getOperation()->cloneWithoutRegions());
1051 if (!isExternal()) {
1052 FunctionType oldType = getFunctionType();
1054 unsigned oldNumArgs = oldType.getNumInputs();
1055 SmallVector<Type, 4> newInputs;
1056 newInputs.reserve(oldNumArgs);
1057 for (
unsigned i = 0; i != oldNumArgs; ++i)
1058 if (!mapper.contains(getArgument(i)))
1059 newInputs.push_back(oldType.getInput(i));
1063 if (newInputs.size() != oldNumArgs) {
1064 newFunc.setType(FunctionType::get(oldType.getContext(), newInputs,
1065 oldType.getResults()));
1067 if (ArrayAttr argAttrs = getAllArgAttrs()) {
1068 SmallVector<Attribute> newArgAttrs;
1069 newArgAttrs.reserve(newInputs.size());
1070 for (
unsigned i = 0; i != oldNumArgs; ++i)
1071 if (!mapper.contains(getArgument(i)))
1072 newArgAttrs.push_back(argAttrs[i]);
1073 newFunc.setAllArgAttrs(newArgAttrs);
1079 cloneInto(newFunc, mapper);
1083FuncOp FuncOp::clone() {
1085 return clone(mapper);
1090void FuncOp::getAsmBlockArgumentNames(mlir::Region ®ion,
1095 for (
auto [arg, name] :
llvm::zip(getArguments(), getArgNames()))
1096 setNameFn(arg, cast<StringAttr>(name).getValue());
1099LogicalResult FuncOp::verify() {
1100 if (getFunctionType().getNumResults() > 1)
1102 "incorrect number of function results (always has to be 0 or 1)");
1104 if (getBody().
empty())
1107 if (getArgNames().size() != getFunctionType().getNumInputs())
1108 return emitOpError(
"incorrect number of argument names");
1110 for (
auto portName : getArgNames()) {
1111 if (cast<StringAttr>(portName).getValue().
empty())
1112 return emitOpError(
"arg name must not be empty");
1118LogicalResult FuncOp::verifyRegions() {
1119 auto attachNote = [&](mlir::InFlightDiagnostic &diag) {
1120 diag.attachNote(
getLoc()) <<
"in function '@" <<
getName() <<
"'";
1133LogicalResult ReturnOp::verify() {
1134 auto function = cast<FuncOp>((*this)->getParentOp());
1137 const auto &results = function.getFunctionType().getResults();
1138 if (getNumOperands() != results.size())
1139 return emitOpError(
"has ")
1140 << getNumOperands() <<
" operands, but enclosing function (@"
1141 << function.getName() <<
") returns " << results.size();
1143 for (
unsigned i = 0, e = results.size(); i != e; ++i)
1144 if (getOperand(i).getType() != results[i])
1145 return emitError() <<
"type of return operand " << i <<
" ("
1146 << getOperand(i).getType()
1147 <<
") doesn't match function result type ("
1148 << results[i] <<
")"
1149 <<
" in function @" << function.getName();
1159#define GET_OP_CLASSES
1160#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.