13#include "mlir/Dialect/Func/IR/FuncOps.h"
14#include "mlir/IR/Builders.h"
15#include "mlir/IR/OpImplementation.h"
16#include "mlir/IR/PatternMatch.h"
17#include "mlir/IR/SymbolTable.h"
18#include "mlir/Interfaces/FunctionImplementation.h"
19#include "mlir/Interfaces/SideEffectInterfaces.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/TypeSwitch.h"
32 TypeRange expectedTypeList,
33 TypeRange actualTypeList,
34 StringRef elementName) {
35 if (expectedTypeList.size() != actualTypeList.size())
36 return op->emitOpError(
"incorrect number of ")
37 << elementName <<
"s: expected " << expectedTypeList.size()
38 <<
", but got " << actualTypeList.size();
40 for (
unsigned i = 0, e = expectedTypeList.size(); i != e; ++i) {
41 if (expectedTypeList[i] != actualTypeList[i]) {
42 auto diag = op->emitOpError(elementName)
43 <<
" type mismatch: " << elementName <<
" #" << i;
44 diag.attachNote() <<
"expected type: " << expectedTypeList[i];
45 diag.attachNote() <<
" actual type: " << actualTypeList[i];
55 SymbolTableCollection &symbolTable) {
57 auto arcName = op->getAttrOfType<FlatSymbolRefAttr>(
"arc");
60 assert(arcName &&
"FlatSymbolRefAttr called 'arc' missing");
61 DefineOp
arc = symbolTable.lookupNearestSymbolFrom<DefineOp>(op, arcName);
63 return op->emitOpError() <<
"`" << arcName.getValue()
64 <<
"` does not reference a valid `arc.define`";
67 auto type =
arc.getFunctionType();
80 return llvm::isa<arc::ModelOp, hw::HWModuleLike>(moduleOp);
86 Operation *pointing, StringAttr symbol) {
87 Operation *moduleOp = symbolTable.lookupNearestSymbolFrom(pointing, symbol);
89 pointing->emitOpError(
"model not found");
94 pointing->emitOpError(
"model symbol does not point to a supported model "
95 "operation, points to ")
96 << moduleOp->getName() <<
" instead";
104 StringRef portName) {
105 auto findRightPort = [&](
auto ports) -> std::optional<hw::ModulePort> {
108 if (port == ports.end())
113 return TypeSwitch<Operation *, std::optional<hw::ModulePort>>(moduleOp)
115 [&](arc::ModelOp modelOp) -> std::optional<hw::ModulePort> {
116 return findRightPort(modelOp.getIo().getPorts());
118 .Case<hw::HWModuleLike>(
119 [&](hw::HWModuleLike moduleLike) -> std::optional<hw::ModulePort> {
120 return findRightPort(moduleLike.getPortList());
122 .Default([](Operation *) {
return std::nullopt; });
129ParseResult DefineOp::parse(OpAsmParser &parser, OperationState &result) {
131 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
132 function_interface_impl::VariadicFlag,
133 std::string &) {
return builder.getFunctionType(argTypes, results); };
135 return function_interface_impl::parseFunctionOp(
136 parser, result,
false,
137 getFunctionTypeAttrName(result.name), buildFuncType,
138 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
141void DefineOp::print(OpAsmPrinter &p) {
142 function_interface_impl::printFunctionOp(
143 p, *
this,
false,
"function_type", getArgAttrsAttrName(),
144 getResAttrsAttrName());
147LogicalResult DefineOp::verifyRegions() {
154 if (isMemoryEffectFree(&op))
163 auto diag = mlir::emitError(
getLoc(),
"body contains non-pure operation");
164 diag.attachNote(op.getLoc()).append(
"first non-pure operation here: ");
170bool DefineOp::isPassthrough() {
171 if (getNumArguments() != getNumResults())
175 llvm::zip(getArguments(),
getBodyBlock().getTerminator()->getOperands()),
176 [](
const auto &argAndRes) {
177 return std::get<0>(argAndRes) == std::get<1>(argAndRes);
185LogicalResult OutputOp::verify() {
186 auto *parent = (*this)->getParentOp();
187 TypeRange expectedTypes = parent->getResultTypes();
188 if (
auto defOp = dyn_cast<DefineOp>(parent))
189 expectedTypes = defOp.getResultTypes();
191 TypeRange actualTypes = getOperands().getTypes();
199LogicalResult StateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
201 getResults().getTypes(), symbolTable);
204LogicalResult StateOp::verify() {
205 if (getLatency() < 1)
206 return emitOpError(
"latency must be a positive integer");
209 return emitOpError(
"requires a clock");
219StateWriteOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
220 if (!getTraceTapModel().has_value())
223 auto modelOp = symbolTable.lookupNearestSymbolFrom<ModelOp>(
224 getOperation(), getTraceTapModelAttr());
226 return emitOpError() <<
"`" << getTraceTapModelAttr()
227 <<
"` does not reference a valid `arc.model`";
228 if (!modelOp.getTraceTaps())
229 return emitOpError() <<
"referenced model has no trace metadata";
230 if (modelOp.getTraceTapsAttr().size() <= *getTraceTapIndex())
231 return emitOpError() <<
"tap index exceeds model's tap array";
233 cast<TraceTapAttr>(modelOp.getTraceTapsAttr()[*getTraceTapIndex()]);
234 if (tapAttr.getSigType().getValue() != getValue().getType())
235 return emitOpError() <<
"incorrect signal type in referenced tap attribute";
240LogicalResult StateWriteOp::verify() {
241 if (getTraceTapIndex().has_value() == getTraceTapModel().has_value())
243 return emitOpError() <<
"must specify both a trace tap model and index";
250LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
252 getResults().getTypes(), symbolTable);
255bool CallOp::isClocked() {
return false; }
257Value CallOp::getClock() {
return Value{}; }
259void CallOp::eraseClock() {}
261uint32_t CallOp::getLatency() {
return 0; }
267SmallVector<Type> MemoryWritePortOp::getArcResultTypes() {
268 auto memType = cast<MemoryType>(getMemory().getType());
269 SmallVector<Type> resultTypes{memType.getAddressType(),
270 memType.getWordType()};
272 resultTypes.push_back(IntegerType::get(getContext(), 1));
274 resultTypes.push_back(memType.getWordType());
279MemoryWritePortOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
284LogicalResult MemoryWritePortOp::verify() {
285 if (getLatency() < 1)
286 return emitOpError(
"latency must be at least 1");
289 return emitOpError(
"requires a clock");
299 SmallString<32> buf(
"in_");
301 setNameFn(getState(), buf);
309 SmallString<32> buf(
"out_");
311 setNameFn(getState(), buf);
318LogicalResult ModelOp::verify() {
320 return emitOpError(
"must have exactly one argument");
321 if (
auto type =
getBodyBlock().getArgument(0).getType();
322 !isa<StorageType>(type))
323 return emitOpError(
"argument must be of storage type");
327LogicalResult ModelOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
328 auto fnAttrs = std::array{getInitialFnAttr(), getFinalFnAttr()};
329 auto nouns = std::array{
"initializer",
"finalizer"};
330 for (
auto [fnAttr, noun] : llvm::zip(fnAttrs, nouns)) {
333 auto fn = symbolTable.lookupNearestSymbolFrom<func::FuncOp>(*
this, fnAttr);
335 return emitOpError() << noun <<
" '" << fnAttr.getValue()
336 <<
"' does not reference a valid function";
337 if (!llvm::equal(fn.getArgumentTypes(), getBody().getArgumentTypes())) {
338 auto diag = emitError() << noun <<
" '" << fnAttr.getValue()
339 <<
"' arguments must match arguments of model";
340 diag.attachNote(fn.getLoc()) << noun <<
" declared here:";
351LogicalResult LutOp::verify() {
352 Location firstSideEffectOpLoc = UnknownLoc::get(getContext());
353 const WalkResult result = getBody().walk([&](Operation *op) {
354 if (
auto memOp = dyn_cast<MemoryEffectOpInterface>(op)) {
355 SmallVector<SideEffects::EffectInstance<MemoryEffects::Effect>> effects;
356 memOp.getEffects(effects);
358 if (!effects.empty()) {
359 firstSideEffectOpLoc = memOp->getLoc();
360 return WalkResult::interrupt();
364 return WalkResult::advance();
367 if (result.wasInterrupted())
368 return emitOpError(
"no operations with side-effects allowed inside a LUT")
369 .attachNote(firstSideEffectOpLoc)
370 <<
"first operation with side-effects here";
379LogicalResult VectorizeOp::verify() {
380 if (getInputs().
empty())
381 return emitOpError(
"there has to be at least one input vector");
383 if (!llvm::all_equal(llvm::map_range(
384 getInputs(), [](OperandRange range) {
return range.size(); })))
385 return emitOpError(
"all input vectors must have the same size");
387 for (OperandRange range : getInputs()) {
388 if (!llvm::all_equal(range.getTypes()))
389 return emitOpError(
"all input vector lane types must match");
392 return emitOpError(
"input vector must have at least one element");
395 if (getResults().
empty())
396 return emitOpError(
"must have at least one result");
398 if (!llvm::all_equal(getResults().getTypes()))
399 return emitOpError(
"all result types must match");
401 if (getResults().size() != getInputs().front().size())
402 return emitOpError(
"number results must match input vector size");
408 if (isa<VectorType>(base))
411 if (
auto vectorTy = dyn_cast<VectorType>(vectorized)) {
412 if (vectorTy.getElementType() != base)
415 return vectorTy.getDimSize(0);
418 if (vectorized.getIntOrFloatBitWidth() < base.getIntOrFloatBitWidth())
421 if (vectorized.getIntOrFloatBitWidth() % base.getIntOrFloatBitWidth() == 0)
422 return vectorized.getIntOrFloatBitWidth() / base.getIntOrFloatBitWidth();
427LogicalResult VectorizeOp::verifyRegions() {
428 auto returnOp = cast<VectorizeReturnOp>(getBody().front().getTerminator());
429 TypeRange bodyArgTypes = getBody().front().getArgumentTypes();
431 if (bodyArgTypes.size() != getInputs().size())
433 "number of block arguments must match number of input vectors");
436 if (returnOp.getValue().getType() == getResultTypes().front()) {
437 for (
auto [i, argTy] : llvm::enumerate(bodyArgTypes))
438 if (argTy != getInputs()[i].getTypes().front())
439 return emitOpError(
"if terminator type matches result type the "
440 "argument types must match the input types");
447 getResultTypes().front());
449 for (
auto [i, argTy] : llvm::enumerate(bodyArgTypes)) {
450 Type inputTy = getInputs()[i].getTypes().front();
452 if (failed(argWidth))
453 return emitOpError(
"block argument must be a scalar variant of the "
454 "vectorized operand");
456 if (*argWidth != width)
457 return emitOpError(
"input and output vector width must match");
465 returnOp.getValue().getType());
467 for (
auto [i, argTy] : llvm::enumerate(bodyArgTypes)) {
468 Type inputTy = getInputs()[i].getTypes().front();
470 if (failed(argWidth))
472 "block argument must be a vectorized variant of the operand");
474 if (*argWidth != width)
475 return emitOpError(
"input and output vector width must match");
477 if (getInputs()[i].size() > 1 && argWidth != getInputs()[i].size())
479 "when boundary not vectorized the number of vector element "
480 "operands must match the width of the vectorized body");
486 return returnOp.emitOpError(
487 "operand type must match parent op's result value or be a vectorized or "
488 "non-vectorized variant of it");
491bool VectorizeOp::isBoundaryVectorized() {
492 return getInputs().front().size() == 1;
494bool VectorizeOp::isBodyVectorized() {
495 auto returnOp = cast<VectorizeReturnOp>(getBody().front().getTerminator());
496 if (isBoundaryVectorized() &&
497 returnOp.getValue().getType() == getResultTypes().front())
501 returnOp.getValue().getType());
512void SimInstantiateOp::print(OpAsmPrinter &p) {
513 BlockArgument modelArg = getBody().getArgument(0);
514 auto modelType = cast<SimModelInstanceType>(modelArg.getType());
516 p <<
" " << modelType.getModel() <<
" as ";
517 p.printRegionArgument(modelArg, {},
true);
519 if (getRuntimeModel() || getRuntimeArgs()) {
521 if (getRuntimeModel())
522 p << getRuntimeModelAttr();
524 if (getRuntimeArgs())
525 p << getRuntimeArgsAttr();
529 p.printOptionalAttrDictWithKeyword(
530 getOperation()->getAttrs(),
531 {getRuntimeModelAttrName(), getRuntimeArgsAttrName()});
535 p.printRegion(getBody(),
false);
538ParseResult SimInstantiateOp::parse(OpAsmParser &parser,
539 OperationState &result) {
540 StringAttr modelName;
541 if (failed(parser.parseSymbolName(modelName)))
544 if (failed(parser.parseKeyword(
"as")))
547 OpAsmParser::Argument modelArg;
548 if (failed(parser.parseArgument(modelArg,
false,
false)))
551 if (succeeded(parser.parseOptionalKeyword(
"runtime"))) {
552 StringAttr runtimeSym;
553 StringAttr runtimeArgs;
554 auto symOpt = parser.parseOptionalSymbolName(runtimeSym);
555 if (parser.parseLParen())
557 auto nameOpt = parser.parseOptionalAttribute(runtimeArgs);
558 if (parser.parseRParen())
560 if (succeeded(symOpt))
562 SimInstantiateOp::getRuntimeModelAttrName(result.name),
563 FlatSymbolRefAttr::get(runtimeSym));
564 if (nameOpt.has_value())
565 result.addAttribute(SimInstantiateOp::getRuntimeArgsAttrName(result.name),
569 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
572 MLIRContext *ctxt = result.getContext();
574 SimModelInstanceType::get(ctxt, FlatSymbolRefAttr::get(ctxt, modelName));
576 std::unique_ptr<Region> body = std::make_unique<Region>();
577 if (failed(parser.parseRegion(*body, {modelArg})))
580 result.addRegion(std::move(body));
584LogicalResult SimInstantiateOp::verifyRegions() {
585 Region &body = getBody();
586 if (body.getNumArguments() != 1)
587 return emitError(
"entry block of body region must have the model instance "
588 "as a single argument");
589 if (!llvm::isa<SimModelInstanceType>(body.getArgument(0).getType()))
590 return emitError(
"entry block argument type is not a model instance");
595SimInstantiateOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
598 symbolTable, getOperation(),
599 llvm::cast<SimModelInstanceType>(getBody().getArgument(0).getType())
605 if (getRuntimeModel().has_value()) {
606 Operation *runtimeModelOp = symbolTable.lookupNearestSymbolFrom(
607 getOperation(), getRuntimeModelAttr());
608 if (!runtimeModelOp) {
609 emitOpError(
"runtime model not found");
611 }
else if (!isa<RuntimeModelOp>(runtimeModelOp)) {
612 emitOpError(
"referenced runtime model is not a RuntimeModelOp");
625SimSetInputOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
627 symbolTable, getOperation(),
628 llvm::cast<SimModelInstanceType>(getInstance().getType())
634 std::optional<hw::ModulePort> port =
getModulePort(moduleOp, getInput());
636 return emitOpError(
"port not found on model");
638 if (port->dir != hw::ModulePort::Direction::Input)
639 return emitOpError(
"port is not an input port");
641 auto portType = port->type;
642 if (
auto inoutType = dyn_cast<hw::InOutType>(portType))
643 portType = inoutType.getElementType();
645 if (portType != getValue().getType())
647 "mismatched types between value and model port, port expects ")
658SimGetPortOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
660 symbolTable, getOperation(),
661 llvm::cast<SimModelInstanceType>(getInstance().getType())
669 return emitOpError(
"port not found on model");
671 if (port->type != getValue().getType())
673 "mismatched types between value and model port, port expects ")
683LogicalResult SimStepOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
685 symbolTable, getOperation(),
686 llvm::cast<SimModelInstanceType>(getInstance().getType())
700SimSetTimeOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
702 symbolTable, getOperation(),
703 llvm::cast<SimModelInstanceType>(getInstance().getType())
719 FlatSymbolRefAttr callee,
722 SymbolTableCollection &symTable) {
724 symTable.lookupNearestSymbolFrom<CoroutineDefineOp>(op, callee);
726 return op->emitOpError() <<
"`" << callee.getValue()
727 <<
"` does not reference a valid "
728 "`arc.coroutine.define`";
730 auto fnType = defineOp.getFunctionType();
740ParseResult CoroutineDefineOp::parse(OpAsmParser &parser,
741 OperationState &result) {
743 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
744 function_interface_impl::VariadicFlag,
745 std::string &) {
return builder.getFunctionType(argTypes, results); };
747 return function_interface_impl::parseFunctionOp(
748 parser, result,
false,
749 getFunctionTypeAttrName(result.name), buildFuncType,
750 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
753void CoroutineDefineOp::print(OpAsmPrinter &p) {
754 function_interface_impl::printFunctionOp(
755 p, *
this,
false,
"function_type", getArgAttrsAttrName(),
756 getResAttrsAttrName());
764CoroutineCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
769 auto callee = (*this)->getAttrOfType<FlatSymbolRefAttr>(
"callee");
771 getResults().getTypes(), symbolTable);
783CoroutineInstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
784 auto callee = (*this)->getAttrOfType<FlatSymbolRefAttr>(
"callee");
786 symbolTable.lookupNearestSymbolFrom<CoroutineDefineOp>(*
this, callee);
788 return emitOpError() <<
"`" << callee.getValue()
789 <<
"` does not reference a valid "
790 "`arc.coroutine.define`";
792 auto fnType = defineOp.getFunctionType();
793 auto fnResults = fnType.getResults();
794 if (fnResults.size() < 2 || !fnResults.back().isInteger(64))
795 return emitOpError() <<
"referenced coroutine `" << callee.getValue()
796 <<
"` must produce an `i64` wakeup time as its "
800 auto maskType = dyn_cast<IntegerType>(fnResults[fnResults.size() - 2]);
801 if (!maskType || maskType.getWidth() != fnType.getNumInputs())
803 <<
"referenced coroutine `" << callee.getValue()
804 <<
"` must produce an observe bitmask with one bit per "
806 << fnType.getNumInputs() <<
"`) as its second-to-last result";
809 getArgs().getTypes(),
"operand")))
812 getResults().getTypes(),
"result")))
826 TypeRange yieldOperands) {
827 auto parent = op->getParentOfType<CoroutineDefineOp>();
832LogicalResult CoroutineYieldOp::verify() {
841 auto parent = (*this)->getParentOfType<CoroutineDefineOp>();
842 TypeRange coroutineArgTypes = parent.getArgumentTypes();
843 TypeRange destArgTypes = getDest()->getArgumentTypes();
844 if (destArgTypes.size() >= coroutineArgTypes.size())
846 *
this, coroutineArgTypes,
847 destArgTypes.take_front(coroutineArgTypes.size()),
848 "destination resume argument")))
859SuccessorOperands CoroutineYieldOp::getSuccessorOperands(
unsigned index) {
860 assert(index == 0 &&
"invalid successor index");
861 auto parent = (*this)->getParentOfType<CoroutineDefineOp>();
862 return SuccessorOperands(parent.getArgumentTypes().size(),
863 getDestOperandsMutable());
866LogicalResult CoroutineReturnOp::verify() {
870LogicalResult CoroutineHaltOp::verify() {
878LogicalResult ExecuteOp::verifyRegions() {
880 getBody().getArgumentTypes(),
"input");
887LogicalResult ArrayRefAllocOp::verify() {
888 if (
auto init = getInit()) {
889 if (init->size() != getType().getNumElements()) {
890 return emitOpError(
"init size does not match array size; init had size ")
891 << init->size() <<
" but array has size "
892 << getType().getNumElements();
895 if (
auto intTy = dyn_cast<IntegerType>(getType().getElementType())) {
896 unsigned elemBitwidth = intTy.getWidth();
897 for (Attribute attr : *init) {
898 auto intAttr = dyn_cast<IntegerAttr>(attr);
899 if (!intAttr || intAttr.getValue().getBitWidth() != elemBitwidth) {
900 return emitOpError(
"expected element to be of type ")
901 << getType().getElementType();
909#include "circt/Dialect/Arc/ArcInterfaces.cpp.inc"
911#define GET_OP_CLASSES
912#include "circt/Dialect/Arc/Arc.cpp.inc"
static FailureOr< unsigned > getVectorWidth(Type base, Type vectorized)
static std::optional< hw::ModulePort > getModulePort(Operation *moduleOp, StringRef portName)
static bool isSupportedModuleOp(Operation *moduleOp)
static LogicalResult verifyArcSymbolUse(Operation *op, TypeRange inputs, TypeRange results, SymbolTableCollection &symbolTable)
static LogicalResult verifyTypeListEquivalence(Operation *op, TypeRange expectedTypeList, TypeRange actualTypeList, StringRef elementName)
static LogicalResult verifyCoroutineCallTypes(Operation *op, FlatSymbolRefAttr callee, TypeRange operands, TypeRange results, SymbolTableCollection &symTable)
Resolve the callee symbol to a CoroutineDefineOp and verify that the given operand and result types m...
static LogicalResult verifyCoroutineTerminator(Operation *op, TypeRange yieldOperands)
static Operation * getSupportedModuleOp(SymbolTableCollection &symbolTable, Operation *pointing, StringAttr symbol)
Fetches the operation pointed to by pointing with name symbol, checking that it is a supported model ...
assert(baseType &&"element must be base type")
static PortInfo getPort(ModuleTy &mod, size_t idx)
static Location getLoc(DefSlot slot)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
static Block * getBodyBlock(FModuleLike mod)
static InstancePath empty
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn