18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/Support/Casting.h"
25#include "mlir/Dialect/EmitC/IR/EmitCDialect.cpp.inc"
36 return emitc::ConstantOp::create(builder, loc, type, value);
42 emitc::YieldOp::create(builder, loc);
46 if (llvm::isa<emitc::OpaqueType>(type))
48 if (
auto ptrType = llvm::dyn_cast<emitc::PointerType>(type))
50 if (
auto arrayType = llvm::dyn_cast<emitc::ArrayType>(type)) {
51 auto elemType = arrayType.getElementType();
52 return !llvm::isa<emitc::ArrayType>(elemType) &&
57 if (llvm::isa<IntegerType>(type))
59 if (llvm::isa<FloatType>(type))
61 if (
auto tensorType = llvm::dyn_cast<TensorType>(type)) {
62 if (!tensorType.hasStaticShape()) {
65 auto elemType = tensorType.getElementType();
66 if (llvm::isa<emitc::ArrayType>(elemType)) {
71 if (
auto tupleType = llvm::dyn_cast<TupleType>(type)) {
72 return llvm::all_of(tupleType.getTypes(), [](
Type type) {
73 return !llvm::isa<emitc::ArrayType>(type) && isSupportedEmitCType(type);
80 if (
auto intType = llvm::dyn_cast<IntegerType>(type)) {
81 switch (intType.getWidth()) {
96 return llvm::isa<IndexType, emitc::OpaqueType>(type) ||
101 if (
auto floatType = llvm::dyn_cast<FloatType>(type)) {
102 switch (floatType.getWidth()) {
104 return llvm::isa<Float16Type, BFloat16Type>(type);
116 return isa<emitc::SignedSizeTType, emitc::SizeTType, emitc::PtrDiffTType>(
123 isa<emitc::PointerType>(type);
130 assert(op->
getNumResults() == 1 &&
"operation must have 1 result");
132 if (llvm::isa<emitc::OpaqueAttr>(value))
135 if (llvm::isa<StringAttr>(value))
137 <<
"string attributes are not supported, use #emitc.opaque instead";
140 if (
auto lType = dyn_cast<LValueType>(resultType))
141 resultType = lType.getValueType();
142 Type attrType = cast<TypedAttr>(value).getType();
147 if (resultType != attrType)
149 <<
"requires attribute to either be an #emitc.opaque attribute or "
151 << attrType <<
") to match the op's result type (" << resultType
162template <
class ArgType>
164 StringRef toParse, ArgType fmtArgs,
169 if (fmtArgs.empty()) {
170 items.push_back(toParse);
174 while (!toParse.empty()) {
175 size_t idx = toParse.find(
'{');
176 if (idx == StringRef::npos) {
178 items.push_back(toParse);
183 items.push_back(toParse.take_front(idx));
184 toParse = toParse.drop_front(idx);
187 if (toParse.size() < 2) {
188 return emitError() <<
"expected '}' after unescaped '{' at end of string";
191 char nextChar = toParse[1];
192 if (nextChar ==
'{') {
194 items.push_back(toParse.take_front(1));
195 toParse = toParse.drop_front(2);
198 if (nextChar ==
'}') {
200 toParse = toParse.drop_front(2);
205 return emitError() <<
"expected '}' after unescaped '{'";
216LogicalResult AddressOfOp::verify() {
217 emitc::LValueType referenceType = getReference().getType();
218 emitc::PointerType resultType = getResult().getType();
220 if (referenceType.getValueType() != resultType.getPointee())
221 return emitOpError(
"requires result to be a pointer to the type "
222 "referenced by operand");
231LogicalResult AddOp::verify() {
232 Type lhsType = getLhs().getType();
233 Type rhsType = getRhs().getType();
235 if (isa<emitc::PointerType>(lhsType) && isa<emitc::PointerType>(rhsType))
236 return emitOpError(
"requires that at most one operand is a pointer");
238 if ((isa<emitc::PointerType>(lhsType) &&
239 !isa<IntegerType, emitc::OpaqueType>(rhsType)) ||
240 (isa<emitc::PointerType>(rhsType) &&
241 !isa<IntegerType, emitc::OpaqueType>(lhsType)))
242 return emitOpError(
"requires that one operand is an integer or of opaque "
243 "type if the other is a pointer");
252template <
typename AssignmentOp>
256 if (!variable.getDefiningOp())
257 return op.emitOpError() <<
"cannot assign to block argument";
259 Type valueType = op.getValue().getType();
260 Type variableType = variable.getType().getValueType();
261 if (variableType != valueType)
262 return op.emitOpError() <<
"requires value's type (" << valueType
263 <<
") to match variable's type (" << variableType
264 <<
")\n variable: " << variable
265 <<
"\n value: " << op.getValue() <<
"\n";
286 Type input = inputs.front(), output = outputs.front();
288 if (
auto arrayType = dyn_cast<emitc::ArrayType>(input)) {
289 if (
auto pointerType = dyn_cast<emitc::PointerType>(output)) {
290 return (arrayType.getElementType() == pointerType.getPointee()) &&
291 arrayType.getShape().size() == 1 && arrayType.getShape()[0] >= 1;
307void emitc::CastOp::getEffects(
322 std::optional<ArrayAttr> args,
323 std::optional<ArrayAttr> templateArgs,
324 TypeRange resultTypes,
size_t numArgsOperands) {
327 return op->
emitOpError(
"callee must not be empty");
331 auto intAttr = llvm::dyn_cast<IntegerAttr>(arg);
332 if (intAttr && llvm::isa<IndexType>(intAttr.getType())) {
337 return op->
emitOpError(
"index argument is out of range");
339 }
else if (llvm::isa<ArrayAttr>(arg)) {
340 return op->
emitOpError(
"array argument has no type");
347 if (!llvm::isa<TypeAttr, IntegerAttr, FloatAttr, emitc::OpaqueAttr>(tArg))
348 return op->
emitOpError(
"template argument has invalid type");
352 if (llvm::any_of(resultTypes, llvm::IsaPred<ArrayType>)) {
353 return op->
emitOpError() <<
"cannot return array type";
359LogicalResult emitc::CallOpaqueOp::verify() {
361 getTemplateArgs(), getResultTypes(),
365LogicalResult emitc::MemberCallOpaqueOp::verify() {
367 getTemplateArgs(), getResultTypes(),
368 getArgOperands().size());
375LogicalResult emitc::ConstantOp::verify() {
379 if (
auto opaqueValue = llvm::dyn_cast<emitc::OpaqueAttr>(value)) {
380 if (opaqueValue.getValue().empty())
381 return emitOpError() <<
"value must not be empty";
386OpFoldResult emitc::ConstantOp::fold(FoldAdaptor adaptor) {
return getValue(); }
392LogicalResult DereferenceOp::verify() {
396 return emitOpError(
"requires result to be an lvalue of the type "
397 "pointed to by operand");
408struct RemoveRecurringExpressionOperands
410 using OpRewritePattern<ExpressionOp>::OpRewritePattern;
411 LogicalResult matchAndRewrite(ExpressionOp expressionOp,
412 PatternRewriter &rewriter)
const override {
417 for (
auto [i, operand] : llvm::enumerate(expressionOp.getDefs())) {
418 if (uniqueOperands.contains(operand))
420 uniqueOperands.insert(operand);
421 firstIndexOf[operand] = i;
425 if (uniqueOperands.size() == expressionOp.getDefs().size())
430 auto uniqueExpression = emitc::ExpressionOp::create(
431 rewriter, expressionOp.getLoc(), expressionOp.getResult().getType(),
432 uniqueOperands.getArrayRef(), expressionOp.getDoNotInline());
433 Block &uniqueExpressionBody = uniqueExpression.createBody();
438 Block *expressionBody = expressionOp.getBody();
439 for (
auto [operand, arg] :
440 llvm::zip(expressionOp.getOperands(), expressionBody->
getArguments()))
441 mapper.
map(arg, uniqueExpressionBody.
getArgument(firstIndexOf[operand]));
444 for (Operation &opToClone : *expressionOp.getBody())
445 rewriter.
clone(opToClone, mapper);
448 rewriter.
replaceOp(expressionOp, uniqueExpression);
459 using OpRewritePattern<ExpressionOp>::OpRewritePattern;
460 LogicalResult matchAndRewrite(ExpressionOp expressionOp,
461 PatternRewriter &rewriter)
const override {
462 auto yieldOp = cast<YieldOp>(expressionOp.getBody()->getTerminator());
463 Value yieldedValue = yieldOp.getResult();
464 auto blockArg = dyn_cast_if_present<BlockArgument>(yieldedValue);
468 expressionOp.getOperand(blockArg.getArgNumber()));
477 results.
add<RemoveRecurringExpressionOperands, FoldTrivialExpressionOp>(
486 result.addAttribute(ExpressionOp::getDoNotInlineAttrName(
result.name),
491 "expected function type");
492 auto fnType = llvm::dyn_cast<FunctionType>(type);
495 "expected function type");
499 if (fnType.getNumResults() != 1)
501 "expected single return type");
502 result.addTypes(fnType.getResults());
506 bool enableNameShadowing = uniqueOperands.size() ==
result.operands.size();
508 if (enableNameShadowing) {
509 for (
auto [unresolvedOperand, operandType] :
510 llvm::zip(operands, fnType.getInputs())) {
512 argInfo.
ssaName = unresolvedOperand;
513 argInfo.
type = operandType;
514 argsInfo.push_back(argInfo);
518 if (parser.
parseRegion(*body, argsInfo, enableNameShadowing))
520 if (!enableNameShadowing) {
523 beforeRegionLoc,
"with recurring operands expected block arguments");
531 auto operands = getDefs();
536 bool printEntryBlockArgs =
true;
537 if (uniqueOperands.size() == operands.size()) {
539 printEntryBlockArgs =
false;
546 auto yieldOp = cast<YieldOp>(getBody()->getTerminator());
547 Value yieldedValue = yieldOp.getResult();
551LogicalResult ExpressionOp::verify() {
552 Type resultType = getResult().getType();
553 Region ®ion = getRegion();
558 return emitOpError(
"must yield a value at termination");
561 Value yieldResult = yield.getResult();
564 return emitOpError(
"must yield a value at termination");
569 return emitOpError(
"yielded value has no defining op");
572 return emitOpError(
"yielded value not defined within expression");
576 if (resultType != yieldType)
577 return emitOpError(
"requires yielded type to match return type");
580 auto expressionInterface = dyn_cast<emitc::CExpressionInterface>(op);
581 if (!expressionInterface)
582 return emitOpError(
"contains an unsupported operation");
583 if (op.getNumResults() != 1)
584 return emitOpError(
"requires exactly one result for each operation");
587 return emitOpError(
"contains an unused operation");
594 worklist.push_back(rootOp);
595 while (!worklist.empty()) {
598 if (visited.contains(op)) {
599 auto cExpr = cast<CExpressionInterface>(op);
600 if (!cExpr.alwaysInline() && cExpr.hasSideEffects())
602 "requires exactly one use for operations with side effects");
606 if (
Operation *def = operand.getDefiningOp()) {
607 worklist.push_back(def);
613 if (getDoNotInline() &&
614 cast<emitc::CExpressionInterface>(rootOp).alwaysInline()) {
615 return emitOpError(
"root operation must be inlined but expression is marked"
637 ForOp::ensureTerminator(*bodyRegion, builder,
result.location);
664 regionArgs.push_back(inductionVariable);
673 regionArgs.front().type = type;
684 ForOp::ensureTerminator(*body, builder,
result.location);
694 p <<
" " << getInductionVar() <<
" = " <<
getLowerBound() <<
" to "
699 p <<
" : " << t <<
' ';
706LogicalResult ForOp::verifyRegions() {
709 if (getBody()->getNumArguments() != 1)
710 return emitOpError(
"expected body to have a single block argument for the "
711 "induction variable");
715 "expected induction variable to be same type as bounds and step");
726 auto fnAttr = getCalleeAttr();
728 return emitOpError(
"requires a 'callee' symbol reference attribute");
731 return emitOpError() <<
"'" << fnAttr.getValue()
732 <<
"' does not reference a valid function";
738FunctionType CallOp::getCalleeType() {
739 return FunctionType::get(
getContext(), getOperandTypes(), getResultTypes());
749 auto fnAttr = getSymNameAttr();
751 return emitOpError(
"requires a 'sym_name' symbol reference attribute");
754 return emitOpError() <<
"'" << fnAttr.getValue()
755 <<
"' does not reference a valid function";
769 state.
addAttribute(getFunctionTypeAttrName(state.
name), TypeAttr::get(type));
773 if (argAttrs.empty())
775 assert(type.getNumInputs() == argAttrs.size());
777 builder, state, argAttrs, {},
778 getArgAttrsAttrName(state.
name), getResAttrsAttrName(state.
name));
789 getFunctionTypeAttrName(
result.name), buildFuncType,
790 getArgAttrsAttrName(
result.name), getResAttrsAttrName(
result.name));
795 p, *
this,
false, getFunctionTypeAttrName(),
796 getArgAttrsAttrName(), getResAttrsAttrName());
799LogicalResult FuncOp::verify() {
800 if (llvm::any_of(getArgumentTypes(), llvm::IsaPred<LValueType>)) {
801 return emitOpError(
"cannot have lvalue type as argument");
804 if (getNumResults() > 1)
805 return emitOpError(
"requires zero or exactly one result, but has ")
808 if (getNumResults() == 1 && isa<ArrayType>(getResultTypes()[0]))
809 return emitOpError(
"cannot return array type");
818LogicalResult ReturnOp::verify() {
819 auto function = cast<FuncOp>((*this)->getParentOp());
822 if (getNumOperands() != function.getNumResults())
823 return emitOpError(
"has ")
824 << getNumOperands() <<
" operands, but enclosing function (@"
825 << function.getName() <<
") returns " << function.getNumResults();
827 if (function.getNumResults() == 1)
828 if (getOperand().
getType() != function.getResultTypes()[0])
829 return emitError() <<
"type of the return operand ("
830 << getOperand().getType()
831 <<
") doesn't match function result type ("
832 << function.getResultTypes()[0] <<
")"
833 <<
" in function @" << function.getName();
842 bool addThenBlock,
bool addElseBlock) {
843 assert((!addElseBlock || addThenBlock) &&
844 "must not create else block w/o then block");
858 bool withElseRegion) {
868 if (withElseRegion) {
876 assert(thenBuilder &&
"the builder callback for 'then' must be present");
883 thenBuilder(builder,
result.location);
889 elseBuilder(builder,
result.location);
895 result.regions.reserve(2);
924 bool printBlockTerminators =
false;
926 p <<
" " << getCondition();
930 printBlockTerminators);
933 Region &elseRegion = getElseRegion();
934 if (!elseRegion.
empty()) {
938 printBlockTerminators);
960 Region *elseRegion = &this->getElseRegion();
961 if (elseRegion->
empty())
974 FoldAdaptor adaptor(operands, *
this);
975 auto boolAttr = dyn_cast_or_null<BoolAttr>(adaptor.getCondition());
976 if (!boolAttr || boolAttr.getValue())
977 regions.emplace_back(&getThenRegion());
980 if (!boolAttr || !boolAttr.getValue()) {
981 if (!getElseRegion().empty())
982 regions.emplace_back(&getElseRegion());
988void IfOp::getRegionInvocationBounds(
991 if (
auto cond = llvm::dyn_cast_or_null<BoolAttr>(operands[0])) {
994 invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
995 invocationBounds.emplace_back(0, cond.getValue() ? 0 : 1);
998 invocationBounds.assign(2, {0, 1});
1007 bool standardInclude = getIsStandardInclude();
1010 if (standardInclude)
1012 p <<
"\"" << getInclude() <<
"\"";
1013 if (standardInclude)
1028 <<
"expected trailing '>' for standard include";
1030 if (standardInclude)
1031 result.addAttribute(
"is_standard_include",
1042LogicalResult emitc::LiteralOp::verify() {
1043 if (getValue().empty())
1044 return emitOpError() <<
"value must not be empty";
1052LogicalResult MemberOp::verify() {
1053 Type operandType = getOperand().getType();
1054 Type resultType = getResult().getType();
1055 bool resultIsWritable = isa<emitc::LValueType, emitc::ArrayType>(resultType);
1065 if (isa<emitc::LValueType>(operandType) && !resultIsWritable)
1066 return emitOpError(
"lvalues must return lvalues or arrays");
1068 if (!isa<emitc::LValueType>(operandType) && resultIsWritable)
1069 return emitOpError(
"non-lvalues cannot return lvalues or arrays");
1078LogicalResult SubOp::verify() {
1079 Type lhsType = getLhs().getType();
1080 Type rhsType = getRhs().getType();
1081 Type resultType = getResult().getType();
1083 if (isa<emitc::PointerType>(rhsType) && !isa<emitc::PointerType>(lhsType))
1084 return emitOpError(
"rhs can only be a pointer if lhs is a pointer");
1086 if (isa<emitc::PointerType>(lhsType) &&
1087 !isa<IntegerType, emitc::OpaqueType, emitc::PointerType>(rhsType))
1088 return emitOpError(
"requires that rhs is an integer, pointer or of opaque "
1089 "type if lhs is a pointer");
1091 if (isa<emitc::PointerType>(lhsType) && isa<emitc::PointerType>(rhsType) &&
1092 !isa<IntegerType, emitc::PtrDiffTType, emitc::OpaqueType>(resultType))
1093 return emitOpError(
"requires that the result is an integer, ptrdiff_t or "
1094 "of opaque type if lhs and rhs are pointers");
1102LogicalResult emitc::VariableOp::verify() {
1110LogicalResult emitc::YieldOp::verify() {
1115 return emitOpError() <<
"yields a value not returned by parent";
1118 return emitOpError() <<
"does not yield a value to be returned by parent";
1120 if (
result && isa<emitc::LValueType>(
result.getType()) &&
1121 !isa<ExpressionOp>(containingOp))
1122 return emitOpError() <<
"yielding lvalues is not supported for this op";
1131LogicalResult emitc::SubscriptOp::verify() {
1133 if (
auto arrayType = llvm::dyn_cast<emitc::ArrayType>(getValue().
getType())) {
1135 if (
getIndices().size() != (
size_t)arrayType.getRank()) {
1136 return emitOpError() <<
"on array operand requires number of indices ("
1138 <<
") to match the rank of the array type ("
1139 << arrayType.getRank() <<
")";
1142 for (
unsigned i = 0, e =
getIndices().size(); i != e; ++i) {
1145 return emitOpError() <<
"on array operand requires index operand " << i
1146 <<
" to be integer-like, but got " << type;
1150 Type elementType = arrayType.getElementType();
1152 if (elementType != resultType) {
1153 return emitOpError() <<
"on array operand requires element type ("
1154 << elementType <<
") and result type (" << resultType
1161 if (
auto pointerType =
1162 llvm::dyn_cast<emitc::PointerType>(getValue().
getType())) {
1165 return emitOpError()
1166 <<
"on pointer operand requires one index operand, but got "
1172 return emitOpError() <<
"on pointer operand requires index operand to be "
1173 "integer-like, but got "
1177 Type pointeeType = pointerType.getPointee();
1179 if (pointeeType != resultType) {
1180 return emitOpError() <<
"on pointer operand requires pointee type ("
1181 << pointeeType <<
") and result type (" << resultType
1196LogicalResult emitc::VerbatimOp::verify() {
1198 return this->emitOpError();
1200 FailureOr<SmallVector<ReplacementItem>> fmt =
1205 size_t numPlaceholders = llvm::count_if(*fmt, [](
ReplacementItem &item) {
1206 return std::holds_alternative<Placeholder>(item);
1209 if (numPlaceholders != getFmtArgs().size()) {
1210 return emitOpError()
1211 <<
"requires operands for each placeholder in the format string";
1216FailureOr<SmallVector<ReplacementItem>> emitc::VerbatimOp::parseFormatString() {
1218 return ::parseFormatString(getValue(), getFmtArgs());
1225#include "mlir/Dialect/EmitC/IR/EmitCEnums.cpp.inc"
1231#define GET_ATTRDEF_CLASSES
1232#include "mlir/Dialect/EmitC/IR/EmitCAttributes.cpp.inc"
1238#define GET_TYPEDEF_CLASSES
1239#include "mlir/Dialect/EmitC/IR/EmitCTypes.cpp.inc"
1260 if (!isValidElementType(elementType))
1261 return parser.
emitError(typeLoc,
"invalid array element type '")
1262 << elementType <<
"'",
1266 return parser.
getChecked<ArrayType>(dimensions, elementType);
1269void emitc::ArrayType::print(
AsmPrinter &printer)
const {
1272 printer << dim <<
'x';
1278LogicalResult emitc::ArrayType::verify(
1282 return emitError() <<
"shape must not be empty";
1286 return emitError() <<
"dimensions must have non-negative size";
1290 return emitError() <<
"element type must not be none";
1292 if (!isValidElementType(elementType))
1293 return emitError() <<
"invalid array element type";
1300 Type elementType)
const {
1302 return emitc::ArrayType::get(
getShape(), elementType);
1303 return emitc::ArrayType::get(*
shape, elementType);
1310LogicalResult mlir::emitc::LValueType::verify(
1317 <<
"!emitc.lvalue must wrap supported emitc type, but got " << value;
1319 if (llvm::isa<emitc::ArrayType>(value))
1320 return emitError() <<
"!emitc.lvalue cannot wrap !emitc.array type";
1329LogicalResult mlir::emitc::OpaqueType::verify(
1331 llvm::StringRef value) {
1332 if (value.empty()) {
1333 return emitError() <<
"expected non empty string in !emitc.opaque type";
1335 if (value.back() ==
'*') {
1336 return emitError() <<
"pointer not allowed as outer type with "
1337 "!emitc.opaque, use !emitc.ptr instead";
1346LogicalResult mlir::emitc::PointerType::verify(
1348 if (llvm::isa<emitc::LValueType>(value))
1349 return emitError() <<
"pointers to lvalues are not allowed";
1368 if (
auto array = llvm::dyn_cast<ArrayType>(type))
1369 return RankedTensorType::get(array.getShape(), array.getElementType());
1380 typeAttr = TypeAttr::get(type);
1388 if (!llvm::isa<ElementsAttr, IntegerAttr, FloatAttr, emitc::OpaqueAttr>(
1391 <<
"initial value should be a integer, float, elements or opaque "
1396LogicalResult GlobalOp::verify() {
1398 return emitOpError(
"expected valid emitc type");
1400 if (getInitialValue().has_value()) {
1401 Attribute initValue = getInitialValue().value();
1404 if (
auto elementsAttr = llvm::dyn_cast<ElementsAttr>(initValue)) {
1405 auto arrayType = llvm::dyn_cast<ArrayType>(
getType());
1407 return emitOpError(
"expected array type, but got ") <<
getType();
1409 Type initType = elementsAttr.getType();
1411 if (initType != tensorType) {
1412 return emitOpError(
"initial value expected to be of type ")
1413 <<
getType() <<
", but was of type " << initType;
1415 }
else if (
auto intAttr = dyn_cast<IntegerAttr>(initValue)) {
1416 if (intAttr.getType() !=
getType()) {
1417 return emitOpError(
"initial value expected to be of type ")
1418 <<
getType() <<
", but was of type " << intAttr.getType();
1420 }
else if (
auto floatAttr = dyn_cast<FloatAttr>(initValue)) {
1421 if (floatAttr.getType() !=
getType()) {
1422 return emitOpError(
"initial value expected to be of type ")
1423 <<
getType() <<
", but was of type " << floatAttr.getType();
1425 }
else if (!isa<emitc::OpaqueAttr>(initValue)) {
1426 return emitOpError(
"initial value should be a integer, float, elements "
1427 "or opaque attribute, but got ")
1431 if (getStaticSpecifier() && getExternSpecifier()) {
1432 return emitOpError(
"cannot have both static and extern specifiers");
1447 return emitOpError(
"'")
1448 << getName() <<
"' does not reference a valid emitc.global";
1450 Type resultType = getResult().getType();
1451 Type globalType = global.getType();
1454 if (llvm::isa<ArrayType>(globalType)) {
1455 if (globalType != resultType)
1456 return emitOpError(
"on array type expects result type ")
1457 << resultType <<
" to match type " << globalType
1458 <<
" of the global @" << getName();
1463 auto lvalueType = dyn_cast<LValueType>(resultType);
1465 return emitOpError(
"on non-array type expects result type to be an "
1466 "lvalue type for the global @")
1468 if (lvalueType.getValueType() != globalType)
1469 return emitOpError(
"on non-array type expects result inner type ")
1470 << lvalueType.getValueType() <<
" to match type " << globalType
1471 <<
" of the global @" << getName();
1486 Region ®ion = *caseRegions.emplace_back(std::make_unique<Region>());
1490 caseValues.push_back(value);
1499 for (
auto [value, region] : llvm::zip(cases.
asArrayRef(), caseRegions)) {
1501 p <<
"case " << value <<
' ';
1507 const Twine &name) {
1508 auto yield = dyn_cast<emitc::YieldOp>(region.
front().
back());
1510 return op.emitOpError(
"expected region to end with emitc.yield, but got ")
1513 if (yield.getNumOperands() != 0) {
1514 return (op.emitOpError(
"expected each region to return ")
1515 <<
"0 values, but " << name <<
" returns "
1516 << yield.getNumOperands())
1517 .attachNote(yield.getLoc())
1518 <<
"see yield operation here";
1524LogicalResult emitc::SwitchOp::verify() {
1526 return emitOpError(
"unsupported type ") << getArg().getType();
1528 if (getCases().size() != getCaseRegions().size()) {
1529 return emitOpError(
"has ")
1530 << getCaseRegions().size() <<
" case regions but "
1531 << getCases().size() <<
" case values";
1535 for (
int64_t value : getCases())
1536 if (!valueSet.insert(value).second)
1537 return emitOpError(
"has duplicate case value: ") << value;
1542 for (
auto [idx, caseRegion] : llvm::enumerate(getCaseRegions()))
1549unsigned emitc::SwitchOp::getNumCases() {
return getCases().size(); }
1551Block &emitc::SwitchOp::getDefaultBlock() {
return getDefaultRegion().
front(); }
1553Block &emitc::SwitchOp::getCaseBlock(
unsigned idx) {
1554 assert(idx < getNumCases() &&
"case index out-of-bounds");
1555 return getCaseRegions()[idx].front();
1558void SwitchOp::getSuccessorRegions(
1560 llvm::append_range(successors, getRegions());
1566 Type type = attr.getType();
1568 return attr.getInt();
1570 return attr.getSInt();
1572 return static_cast<int64_t>(attr.getUInt());
1573 return std::nullopt;
1576void SwitchOp::getEntrySuccessorRegions(
1579 FoldAdaptor adaptor(operands, *
this);
1582 auto arg = dyn_cast_or_null<IntegerAttr>(adaptor.getArg());
1584 llvm::append_range(successors, getRegions());
1591 llvm::append_range(successors, getRegions());
1597 for (
auto [caseValue, caseRegion] : llvm::zip(getCases(), getCaseRegions())) {
1598 if (caseValue == *argValue) {
1599 successors.emplace_back(&caseRegion);
1603 successors.emplace_back(&getDefaultRegion());
1606void SwitchOp::getRegionInvocationBounds(
1608 auto operandValue = llvm::dyn_cast_or_null<IntegerAttr>(operands.front());
1609 if (!operandValue) {
1616 if (!maybeIntValue) {
1622 unsigned liveIndex = getNumRegions() - 1;
1623 const auto *iteratorToInt = llvm::find(getCases(), *maybeIntValue);
1625 liveIndex = iteratorToInt != getCases().end()
1626 ? std::distance(getCases().begin(), iteratorToInt)
1629 for (
unsigned regIndex = 0, regNum = getNumRegions(); regIndex < regNum;
1631 bounds.emplace_back(0, regIndex == liveIndex);
1658 if (
auto array = llvm::dyn_cast<ArrayType>(type))
1659 return RankedTensorType::get(array.getShape(), array.getElementType());
1670 typeAttr = TypeAttr::get(type);
1678 if (!llvm::isa<ElementsAttr, IntegerAttr, FloatAttr, emitc::OpaqueAttr>(
1681 <<
"initial value should be a integer, float, elements or opaque "
1686LogicalResult FieldOp::verify() {
1688 return emitOpError(
"expected valid emitc type");
1691 if (!parentOp || !isa<emitc::ClassOp>(parentOp))
1692 return emitOpError(
"field must be nested within an emitc.class operation");
1694 StringAttr symName = getSymNameAttr();
1695 if (!symName || symName.getValue().empty())
1696 return emitOpError(
"field must have a non-empty symbol name");
1710 return emitOpError(
"field '")
1711 << fieldNameAttr <<
"' not found in the class";
1713 Type getFieldResultType = getResult().getType();
1714 Type fieldType = fieldOp.getType();
1716 if (fieldType != getFieldResultType)
1717 return emitOpError(
"result type ")
1718 << getFieldResultType <<
" does not match field '" << fieldNameAttr
1719 <<
"' type " << fieldType;
1734 getOperation()->getDiscardableAttrDictionary().getValue());
1737LogicalResult emitc::DoOp::verify() {
1738 Block &condBlock = getConditionRegion().
front();
1742 "condition region must contain exactly two operations: "
1743 "'emitc.expression' followed by 'emitc.yield', but found ")
1747 auto exprOp = dyn_cast<emitc::ExpressionOp>(first);
1749 return emitOpError(
"expected first op in condition region to be "
1750 "'emitc.expression', but got ")
1753 if (!exprOp.getResult().getType().isInteger(1))
1754 return emitOpError(
"emitc.expression in condition region must return "
1755 "'i1', but returns ")
1756 << exprOp.getResult().getType();
1759 auto condYield = dyn_cast<emitc::YieldOp>(last);
1761 return emitOpError(
"expected last op in condition region to be "
1762 "'emitc.yield', but got ")
1765 if (condYield.getNumOperands() != 1)
1766 return emitOpError(
"expected condition region to return 1 value, but "
1768 << condYield.getNumOperands() <<
" values";
1770 if (condYield.getOperand(0) != exprOp.getResult())
1771 return emitError(
"'emitc.yield' must return result of "
1772 "'emitc.expression' from this condition region");
1776 return emitOpError(
"body region must not contain terminator");
1789 if (bodyRegion->
empty())
1799#include "mlir/Dialect/EmitC/IR/EmitCInterfaces.cpp.inc"
1801#define GET_OP_CLASSES
1802#include "mlir/Dialect/EmitC/IR/EmitC.cpp.inc"
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
static std::optional< int64_t > getLowerBound(Value iv)
Gets the constant lower bound on an iv.
static std::optional< int64_t > getIntAttrValue(IntegerAttr attr)
Returns the int64_t value of an IntegerAttr regardless of whether its type is signless,...
static LogicalResult verifyInitializationAttribute(Operation *op, Attribute value)
Check that the type of the initial value is compatible with the operations result type.
static LogicalResult verifyRegion(emitc::SwitchOp op, Region ®ion, const Twine &name)
static ParseResult parseEmitCGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValue)
static Type getInitializerTypeForField(Type type)
static ParseResult parseEmitCFieldOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValue)
FailureOr< SmallVector< ReplacementItem > > parseFormatString(StringRef toParse, ArgType fmtArgs, llvm::function_ref< mlir::InFlightDiagnostic()> emitError={})
Parse a format string and return a list of its parts.
static void printEmitCGlobalOpTypeAndInitialValue(OpAsmPrinter &p, GlobalOp op, TypeAttr type, Attribute initialValue)
static LogicalResult verifyAssignmentOp(AssignmentOp op)
static ParseResult parseSwitchCases(OpAsmParser &parser, DenseI64ArrayAttr &cases, SmallVectorImpl< std::unique_ptr< Region > > &caseRegions)
Parse the case regions and values.
static LogicalResult verifyOpaqueCallCommon(Operation *op, StringRef callee, std::optional< ArrayAttr > args, std::optional< ArrayAttr > templateArgs, TypeRange resultTypes, size_t numArgsOperands)
static void printEmitCFieldOpTypeAndInitialValue(OpAsmPrinter &p, FieldOp op, TypeAttr type, Attribute initialValue)
static void printSwitchCases(OpAsmPrinter &p, Operation *op, DenseI64ArrayAttr cases, RegionRange caseRegions)
Print the case regions and values.
static Type getInitializerTypeForGlobal(Type type)
static Type getValueType(Attribute attr)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseOptionalGreater()=0
Parse a '>' token if present.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual OptionalParseResult parseOptionalAttribute(Attribute &result, Type type={})=0
Parse an arbitrary optional attribute of a given type and return it in result.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual void printType(Type type)
virtual void printNewline()
Print a newline and indent the printer to the start of the current operation/attribute/type.
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
OpListType & getOperations()
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
BlockArgListType getArguments()
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
This class is a general helper class for creating context-global objects like types,...
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
IntegerType getIntegerType(unsigned width)
StringAttr getStringAttr(const Twine &bytes)
NamedAttribute getNamedAttr(StringRef name, Attribute val)
A symbol reference with a reference path containing a single element.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
This class represents a diagnostic that is inflight and set to be reported.
This class represents upper and lower bounds on the number of times a region of a RegionBranchOpInter...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
void push_back(NamedAttribute newAttribute)
Add an attribute with the specified name.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void shadowRegionArgs(Region ®ion, ValueRange namesToUse)=0
Renumber the arguments for the specified region to the same names as the SSA values in namesToUse.
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents a single result from folding an operation.
type_range getType() const
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
OperationName getName()
The name of an operation is the key identifier for it.
operand_range getOperands()
Returns an iterator on the underlying Value's.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class provides an abstraction over the different types of ranges over Regions.
This class represents a successor of a region.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
static DerivedEffect * get()
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
ArrayRef< T > asArrayRef() const
A named class for passing around the variadic flag.
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
LogicalResult verifyCallOpInterface(CallOpInterface call, TypeRange argumentTypes, TypeRange resultTypes)
Verify that the forwarded operands and results of call are in a 1:1 relationship with the given argum...
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
void buildTerminatedBody(OpBuilder &builder, Location loc)
Default callback for builders of ops carrying a region.
std::variant< StringRef, Placeholder > ReplacementItem
bool isFundamentalType(mlir::Type type)
Determines whether type is a valid fundamental C++ type in EmitC.
bool isSupportedFloatType(mlir::Type type)
Determines whether type is a valid floating-point type in EmitC.
bool isSupportedEmitCType(mlir::Type type)
Determines whether type is valid in EmitC.
bool isPointerWideType(mlir::Type type)
Determines whether type is a emitc.size_t/ssize_t type.
bool isIntegerIndexOrOpaqueType(Type type)
Determines whether type is integer like, i.e.
bool isSupportedIntegerType(mlir::Type type)
Determines whether type is a valid integer type in EmitC.
void printFunctionOp(OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic, StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName)
Printer implementation for function-like operations.
ParseResult parseFunctionOp(OpAsmParser &parser, OperationState &result, bool allowVariadic, StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder, StringAttr argAttrsName, StringAttr resAttrsName)
Parser implementation for function-like operations.
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
llvm::function_ref< Fn > function_ref
UnresolvedOperand ssaName
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.