Loading [MathJax]/extensions/tex2jax.js
CIRCT 21.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
RTGOps.cpp
Go to the documentation of this file.
1//===- RTGOps.cpp - Implement the RTG operations --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the RTG ops.
10//
11//===----------------------------------------------------------------------===//
12
15#include "mlir/IR/Builders.h"
16#include "mlir/IR/DialectImplementation.h"
17#include "llvm/ADT/SmallString.h"
18
19using namespace mlir;
20using namespace circt;
21using namespace rtg;
22
23//===----------------------------------------------------------------------===//
24// ConstantOp
25//===----------------------------------------------------------------------===//
26
27LogicalResult
28ConstantOp::inferReturnTypes(MLIRContext *context, std::optional<Location> loc,
29 ValueRange operands, DictionaryAttr attributes,
30 OpaqueProperties properties, RegionRange regions,
31 SmallVectorImpl<Type> &inferredReturnTypes) {
32 inferredReturnTypes.push_back(
33 properties.as<Properties *>()->getValue().getType());
34 return success();
35}
36
37OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) { return getValueAttr(); }
38
39//===----------------------------------------------------------------------===//
40// SequenceOp
41//===----------------------------------------------------------------------===//
42
43LogicalResult SequenceOp::verifyRegions() {
44 if (TypeRange(getSequenceType().getElementTypes()) !=
45 getBody()->getArgumentTypes())
46 return emitOpError("sequence type does not match block argument types");
47
48 return success();
49}
50
51ParseResult SequenceOp::parse(OpAsmParser &parser, OperationState &result) {
52 // Parse the name as a symbol.
53 if (parser.parseSymbolName(
54 result.getOrAddProperties<SequenceOp::Properties>().sym_name))
55 return failure();
56
57 // Parse the function signature.
58 SmallVector<OpAsmParser::Argument> arguments;
59 if (parser.parseArgumentList(arguments, OpAsmParser::Delimiter::Paren,
60 /*allowType=*/true, /*allowAttrs=*/true))
61 return failure();
62
63 SmallVector<Type> argTypes;
64 SmallVector<Location> argLocs;
65 argTypes.reserve(arguments.size());
66 argLocs.reserve(arguments.size());
67 for (auto &arg : arguments) {
68 argTypes.push_back(arg.type);
69 argLocs.push_back(arg.sourceLoc ? *arg.sourceLoc : result.location);
70 }
71 Type type = SequenceType::get(result.getContext(), argTypes);
72 result.getOrAddProperties<SequenceOp::Properties>().sequenceType =
73 TypeAttr::get(type);
74
75 auto loc = parser.getCurrentLocation();
76 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
77 return failure();
78 if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() {
79 return parser.emitError(loc)
80 << "'" << result.name.getStringRef() << "' op ";
81 })))
82 return failure();
83
84 std::unique_ptr<Region> bodyRegionRegion = std::make_unique<Region>();
85 if (parser.parseRegion(*bodyRegionRegion, arguments))
86 return failure();
87
88 if (bodyRegionRegion->empty()) {
89 bodyRegionRegion->emplaceBlock();
90 bodyRegionRegion->addArguments(argTypes, argLocs);
91 }
92 result.addRegion(std::move(bodyRegionRegion));
93
94 return success();
95}
96
97void SequenceOp::print(OpAsmPrinter &p) {
98 p << ' ';
99 p.printSymbolName(getSymNameAttr().getValue());
100 p << "(";
101 llvm::interleaveComma(getBody()->getArguments(), p,
102 [&](auto arg) { p.printRegionArgument(arg); });
103 p << ")";
104 p.printOptionalAttrDictWithKeyword(
105 (*this)->getAttrs(), {getSymNameAttrName(), getSequenceTypeAttrName()});
106 p << ' ';
107 p.printRegion(getBodyRegion(), /*printEntryBlockArgs=*/false);
108}
109
110//===----------------------------------------------------------------------===//
111// GetSequenceOp
112//===----------------------------------------------------------------------===//
113
114LogicalResult
115GetSequenceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
116 SequenceOp seq =
117 symbolTable.lookupNearestSymbolFrom<SequenceOp>(*this, getSequenceAttr());
118 if (!seq)
119 return emitOpError()
120 << "'" << getSequence()
121 << "' does not reference a valid 'rtg.sequence' operation";
122
123 if (seq.getSequenceType() != getType())
124 return emitOpError("referenced 'rtg.sequence' op's type does not match");
125
126 return success();
127}
128
129//===----------------------------------------------------------------------===//
130// SubstituteSequenceOp
131//===----------------------------------------------------------------------===//
132
133LogicalResult SubstituteSequenceOp::verify() {
134 if (getReplacements().empty())
135 return emitOpError("must at least have one replacement value");
136
137 if (getReplacements().size() >
138 getSequence().getType().getElementTypes().size())
139 return emitOpError(
140 "must not have more replacement values than sequence arguments");
141
142 if (getReplacements().getTypes() !=
143 getSequence().getType().getElementTypes().take_front(
144 getReplacements().size()))
145 return emitOpError("replacement types must match the same number of "
146 "sequence argument types from the front");
147
148 return success();
149}
150
151LogicalResult SubstituteSequenceOp::inferReturnTypes(
152 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
153 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
154 SmallVectorImpl<Type> &inferredReturnTypes) {
155 ArrayRef<Type> argTypes =
156 cast<SequenceType>(operands[0].getType()).getElementTypes();
157 auto seqType =
158 SequenceType::get(context, argTypes.drop_front(operands.size() - 1));
159 inferredReturnTypes.push_back(seqType);
160 return success();
161}
162
163ParseResult SubstituteSequenceOp::parse(::mlir::OpAsmParser &parser,
164 ::mlir::OperationState &result) {
165 OpAsmParser::UnresolvedOperand sequenceRawOperand;
166 SmallVector<OpAsmParser::UnresolvedOperand, 4> replacementsOperands;
167 Type sequenceRawType;
168
169 if (parser.parseOperand(sequenceRawOperand) || parser.parseLParen())
170 return failure();
171
172 auto replacementsOperandsLoc = parser.getCurrentLocation();
173 if (parser.parseOperandList(replacementsOperands) || parser.parseRParen() ||
174 parser.parseColon() || parser.parseType(sequenceRawType) ||
175 parser.parseOptionalAttrDict(result.attributes))
176 return failure();
177
178 if (!isa<SequenceType>(sequenceRawType))
179 return parser.emitError(parser.getNameLoc())
180 << "'sequence' must be handle to a sequence or sequence family, but "
181 "got "
182 << sequenceRawType;
183
184 if (parser.resolveOperand(sequenceRawOperand, sequenceRawType,
185 result.operands))
186 return failure();
187
188 if (parser.resolveOperands(replacementsOperands,
189 cast<SequenceType>(sequenceRawType)
190 .getElementTypes()
191 .take_front(replacementsOperands.size()),
192 replacementsOperandsLoc, result.operands))
193 return failure();
194
195 SmallVector<Type> inferredReturnTypes;
196 if (failed(inferReturnTypes(
197 parser.getContext(), result.location, result.operands,
198 result.attributes.getDictionary(parser.getContext()),
199 result.getRawProperties(), result.regions, inferredReturnTypes)))
200 return failure();
201
202 result.addTypes(inferredReturnTypes);
203 return success();
204}
205
206void SubstituteSequenceOp::print(OpAsmPrinter &p) {
207 p << ' ' << getSequence() << "(" << getReplacements()
208 << ") : " << getSequence().getType();
209 p.printOptionalAttrDict((*this)->getAttrs(), {});
210}
211
212//===----------------------------------------------------------------------===//
213// InterleaveSequencesOp
214//===----------------------------------------------------------------------===//
215
216LogicalResult InterleaveSequencesOp::verify() {
217 if (getSequences().empty())
218 return emitOpError("must have at least one sequence in the list");
219
220 return success();
221}
222
223OpFoldResult InterleaveSequencesOp::fold(FoldAdaptor adaptor) {
224 if (getSequences().size() == 1)
225 return getSequences()[0];
226
227 return {};
228}
229
230//===----------------------------------------------------------------------===//
231// SetCreateOp
232//===----------------------------------------------------------------------===//
233
234ParseResult SetCreateOp::parse(OpAsmParser &parser, OperationState &result) {
235 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> operands;
236 Type elemType;
237
238 if (parser.parseOperandList(operands) ||
239 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
240 parser.parseType(elemType))
241 return failure();
242
243 result.addTypes({SetType::get(result.getContext(), elemType)});
244
245 for (auto operand : operands)
246 if (parser.resolveOperand(operand, elemType, result.operands))
247 return failure();
248
249 return success();
250}
251
252void SetCreateOp::print(OpAsmPrinter &p) {
253 p << " ";
254 p.printOperands(getElements());
255 p.printOptionalAttrDict((*this)->getAttrs());
256 p << " : " << getSet().getType().getElementType();
257}
258
259LogicalResult SetCreateOp::verify() {
260 if (getElements().size() > 0) {
261 // We only need to check the first element because of the `SameTypeOperands`
262 // trait.
263 if (getElements()[0].getType() != getSet().getType().getElementType())
264 return emitOpError() << "operand types must match set element type";
265 }
266
267 return success();
268}
269
270//===----------------------------------------------------------------------===//
271// SetCartesianProductOp
272//===----------------------------------------------------------------------===//
273
274LogicalResult SetCartesianProductOp::inferReturnTypes(
275 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
276 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
277 SmallVectorImpl<Type> &inferredReturnTypes) {
278 if (operands.empty()) {
279 if (loc)
280 return mlir::emitError(*loc) << "at least one set must be provided";
281 return failure();
282 }
283
284 SmallVector<Type> elementTypes;
285 for (auto operand : operands)
286 elementTypes.push_back(cast<SetType>(operand.getType()).getElementType());
287 inferredReturnTypes.push_back(
288 SetType::get(TupleType::get(context, elementTypes)));
289 return success();
290}
291
292//===----------------------------------------------------------------------===//
293// BagCreateOp
294//===----------------------------------------------------------------------===//
295
296ParseResult BagCreateOp::parse(OpAsmParser &parser, OperationState &result) {
297 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 16> elementOperands,
298 multipleOperands;
299 Type elemType;
300
301 if (!parser.parseOptionalLParen()) {
302 while (true) {
303 OpAsmParser::UnresolvedOperand elementOperand, multipleOperand;
304 if (parser.parseOperand(multipleOperand) || parser.parseKeyword("x") ||
305 parser.parseOperand(elementOperand))
306 return failure();
307
308 elementOperands.push_back(elementOperand);
309 multipleOperands.push_back(multipleOperand);
310
311 if (parser.parseOptionalComma()) {
312 if (parser.parseRParen())
313 return failure();
314 break;
315 }
316 }
317 }
318
319 if (parser.parseColon() || parser.parseType(elemType) ||
320 parser.parseOptionalAttrDict(result.attributes))
321 return failure();
322
323 result.addTypes({BagType::get(result.getContext(), elemType)});
324
325 for (auto operand : elementOperands)
326 if (parser.resolveOperand(operand, elemType, result.operands))
327 return failure();
328
329 for (auto operand : multipleOperands)
330 if (parser.resolveOperand(operand, IndexType::get(result.getContext()),
331 result.operands))
332 return failure();
333
334 return success();
335}
336
337void BagCreateOp::print(OpAsmPrinter &p) {
338 p << " ";
339 if (!getElements().empty())
340 p << "(";
341 llvm::interleaveComma(llvm::zip(getElements(), getMultiples()), p,
342 [&](auto elAndMultiple) {
343 auto [el, multiple] = elAndMultiple;
344 p << multiple << " x " << el;
345 });
346 if (!getElements().empty())
347 p << ")";
348
349 p << " : " << getBag().getType().getElementType();
350 p.printOptionalAttrDict((*this)->getAttrs());
351}
352
353LogicalResult BagCreateOp::verify() {
354 if (!llvm::all_equal(getElements().getTypes()))
355 return emitOpError() << "types of all elements must match";
356
357 if (getElements().size() > 0)
358 if (getElements()[0].getType() != getBag().getType().getElementType())
359 return emitOpError() << "operand types must match bag element type";
360
361 return success();
362}
363
364//===----------------------------------------------------------------------===//
365// TupleCreateOp
366//===----------------------------------------------------------------------===//
367
368LogicalResult TupleCreateOp::inferReturnTypes(
369 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
370 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
371 SmallVectorImpl<Type> &inferredReturnTypes) {
372 if (operands.empty()) {
373 if (loc)
374 return mlir::emitError(*loc) << "empty tuples not allowed";
375 return failure();
376 }
377
378 SmallVector<Type> elementTypes;
379 for (auto operand : operands)
380 elementTypes.push_back(operand.getType());
381 inferredReturnTypes.push_back(TupleType::get(context, elementTypes));
382 return success();
383}
384
385//===----------------------------------------------------------------------===//
386// TupleExtractOp
387//===----------------------------------------------------------------------===//
388
389LogicalResult TupleExtractOp::inferReturnTypes(
390 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
391 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
392 SmallVectorImpl<Type> &inferredReturnTypes) {
393 assert(operands.size() == 1 && "must have exactly one operand");
394
395 auto tupleTy = dyn_cast<TupleType>(operands[0].getType());
396 size_t idx = properties.as<Properties *>()->getIndex().getInt();
397 if (!tupleTy || tupleTy.getTypes().size() <= idx) {
398 if (loc)
399 return mlir::emitError(*loc)
400 << "index (" << idx
401 << ") must be smaller than number of elements in tuple ("
402 << tupleTy.getTypes().size() << ")";
403 return failure();
404 }
405
406 inferredReturnTypes.push_back(tupleTy.getTypes()[idx]);
407 return success();
408}
409
410//===----------------------------------------------------------------------===//
411// FixedRegisterOp
412//===----------------------------------------------------------------------===//
413
414LogicalResult FixedRegisterOp::inferReturnTypes(
415 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
416 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
417 SmallVectorImpl<Type> &inferredReturnTypes) {
418 inferredReturnTypes.push_back(
419 properties.as<Properties *>()->getReg().getType());
420 return success();
421}
422
423OpFoldResult FixedRegisterOp::fold(FoldAdaptor adaptor) { return getRegAttr(); }
424
425//===----------------------------------------------------------------------===//
426// VirtualRegisterOp
427//===----------------------------------------------------------------------===//
428
429LogicalResult VirtualRegisterOp::verify() {
430 if (getAllowedRegs().empty())
431 return emitOpError("must have at least one allowed register");
432
433 if (llvm::any_of(getAllowedRegs(), [](Attribute attr) {
434 return !isa<RegisterAttrInterface>(attr);
435 }))
436 return emitOpError("all elements must be of RegisterAttrInterface");
437
438 if (!llvm::all_equal(
439 llvm::map_range(getAllowedRegs().getAsRange<RegisterAttrInterface>(),
440 [](auto attr) { return attr.getType(); })))
441 return emitOpError("all allowed registers must be of the same type");
442
443 return success();
444}
445
446LogicalResult VirtualRegisterOp::inferReturnTypes(
447 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
448 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
449 SmallVectorImpl<Type> &inferredReturnTypes) {
450 auto allowedRegs = properties.as<Properties *>()->getAllowedRegs();
451 if (allowedRegs.empty()) {
452 if (loc)
453 return mlir::emitError(*loc, "must have at least one allowed register");
454
455 return failure();
456 }
457
458 auto regAttr = dyn_cast<RegisterAttrInterface>(allowedRegs[0]);
459 if (!regAttr) {
460 if (loc)
461 return mlir::emitError(
462 *loc, "allowed register attributes must be of RegisterAttrInterface");
463
464 return failure();
465 }
466 inferredReturnTypes.push_back(regAttr.getType());
467 return success();
468}
469
470//===----------------------------------------------------------------------===//
471// ContextSwitchOp
472//===----------------------------------------------------------------------===//
473
474LogicalResult ContextSwitchOp::verify() {
475 auto elementTypes = getSequence().getType().getElementTypes();
476 if (elementTypes.size() != 3)
477 return emitOpError("sequence type must have exactly 3 element types");
478
479 if (getFrom().getType() != elementTypes[0])
480 return emitOpError(
481 "first sequence element type must match 'from' attribute type");
482
483 if (getTo().getType() != elementTypes[1])
484 return emitOpError(
485 "second sequence element type must match 'to' attribute type");
486
487 auto seqTy = dyn_cast<SequenceType>(elementTypes[2]);
488 if (!seqTy || !seqTy.getElementTypes().empty())
489 return emitOpError(
490 "third sequence element type must be a fully substituted sequence");
491
492 return success();
493}
494
495//===----------------------------------------------------------------------===//
496// TestOp
497//===----------------------------------------------------------------------===//
498
499LogicalResult TestOp::verifyRegions() {
500 if (!getTargetType().entryTypesMatch(getBody()->getArgumentTypes()))
501 return emitOpError("argument types must match dict entry types");
502
503 return success();
504}
505
506LogicalResult TestOp::verify() {
507 if (getTemplateName().empty())
508 return emitOpError("template name must not be empty");
509
510 return success();
511}
512
513LogicalResult TestOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
514 if (!getTargetAttr())
515 return success();
516
517 auto target =
518 symbolTable.lookupNearestSymbolFrom<TargetOp>(*this, getTargetAttr());
519 if (!target)
520 return emitOpError()
521 << "'" << *getTarget()
522 << "' does not reference a valid 'rtg.target' operation";
523
524 // Check if target is a subtype of test requirements
525 // Since entries are sorted by name, we can do this in a single pass
526 size_t targetIdx = 0;
527 auto targetEntries = target.getTarget().getEntries();
528 for (auto testEntry : getTargetType().getEntries()) {
529 // Find the matching entry in target entries.
530 while (targetIdx < targetEntries.size() &&
531 targetEntries[targetIdx].name.getValue() < testEntry.name.getValue())
532 targetIdx++;
533
534 // Check if we found a matching entry with the same name and type
535 if (targetIdx >= targetEntries.size() ||
536 targetEntries[targetIdx].name != testEntry.name ||
537 targetEntries[targetIdx].type != testEntry.type) {
538 return emitOpError("referenced 'rtg.target' op's type is invalid: "
539 "missing entry called '")
540 << testEntry.name.getValue() << "' of type " << testEntry.type;
541 }
542 }
543
544 return success();
545}
546
547ParseResult TestOp::parse(OpAsmParser &parser, OperationState &result) {
548 // Parse the name as a symbol.
549 StringAttr symNameAttr;
550 if (parser.parseSymbolName(symNameAttr))
551 return failure();
552
553 result.getOrAddProperties<TestOp::Properties>().sym_name = symNameAttr;
554
555 // Parse the function signature.
556 SmallVector<OpAsmParser::Argument> arguments;
557 SmallVector<StringAttr> names;
558
559 auto parseOneArgument = [&]() -> ParseResult {
560 std::string name;
561 if (parser.parseKeywordOrString(&name) || parser.parseEqual() ||
562 parser.parseArgument(arguments.emplace_back(), /*allowType=*/true,
563 /*allowAttrs=*/true))
564 return failure();
565
566 names.push_back(StringAttr::get(result.getContext(), name));
567 return success();
568 };
569 if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
570 parseOneArgument, " in argument list"))
571 return failure();
572
573 SmallVector<Type> argTypes;
574 SmallVector<DictEntry> entries;
575 SmallVector<Location> argLocs;
576 argTypes.reserve(arguments.size());
577 argLocs.reserve(arguments.size());
578 for (auto [name, arg] : llvm::zip(names, arguments)) {
579 argTypes.push_back(arg.type);
580 argLocs.push_back(arg.sourceLoc ? *arg.sourceLoc : result.location);
581 entries.push_back({name, arg.type});
582 }
583 auto emitError = [&]() -> InFlightDiagnostic {
584 return parser.emitError(parser.getCurrentLocation());
585 };
586 Type type = DictType::getChecked(emitError, result.getContext(),
587 ArrayRef<DictEntry>(entries));
588 if (!type)
589 return failure();
590 result.getOrAddProperties<TestOp::Properties>().targetType =
591 TypeAttr::get(type);
592
593 std::string templateName;
594 if (!parser.parseOptionalKeyword("template")) {
595 auto loc = parser.getCurrentLocation();
596 if (parser.parseString(&templateName))
597 return failure();
598
599 if (templateName.empty())
600 return parser.emitError(loc, "template name must not be empty");
601 }
602
603 StringAttr templateNameAttr = symNameAttr;
604 if (!templateName.empty())
605 templateNameAttr = StringAttr::get(result.getContext(), templateName);
606
607 StringAttr targetName;
608 if (!parser.parseOptionalKeyword("target"))
609 if (parser.parseSymbolName(targetName))
610 return failure();
611
612 result.getOrAddProperties<TestOp::Properties>().templateName =
613 templateNameAttr;
614 result.getOrAddProperties<TestOp::Properties>().target = targetName;
615
616 auto loc = parser.getCurrentLocation();
617 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
618 return failure();
619 if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() {
620 return parser.emitError(loc)
621 << "'" << result.name.getStringRef() << "' op ";
622 })))
623 return failure();
624
625 std::unique_ptr<Region> bodyRegionRegion = std::make_unique<Region>();
626 if (parser.parseRegion(*bodyRegionRegion, arguments))
627 return failure();
628
629 if (bodyRegionRegion->empty()) {
630 bodyRegionRegion->emplaceBlock();
631 bodyRegionRegion->addArguments(argTypes, argLocs);
632 }
633 result.addRegion(std::move(bodyRegionRegion));
634
635 return success();
636}
637
638void TestOp::print(OpAsmPrinter &p) {
639 p << ' ';
640 p.printSymbolName(getSymNameAttr().getValue());
641 p << "(";
642 SmallString<32> resultNameStr;
643 llvm::interleaveComma(
644 llvm::zip(getTargetType().getEntries(), getBody()->getArguments()), p,
645 [&](auto entryAndArg) {
646 auto [entry, arg] = entryAndArg;
647 p << entry.name.getValue() << " = ";
648 p.printRegionArgument(arg);
649 });
650 p << ")";
651
652 if (getSymNameAttr() != getTemplateNameAttr())
653 p << " template " << getTemplateNameAttr();
654
655 if (getTargetAttr()) {
656 p << " target ";
657 p.printSymbolName(getTargetAttr().getValue());
658 }
659
660 p.printOptionalAttrDictWithKeyword(
661 (*this)->getAttrs(), {getSymNameAttrName(), getTargetTypeAttrName(),
662 getTargetAttrName(), getTemplateNameAttrName()});
663 p << ' ';
664 p.printRegion(getBodyRegion(), /*printEntryBlockArgs=*/false);
665}
666
667void TestOp::getAsmBlockArgumentNames(Region &region,
668 OpAsmSetValueNameFn setNameFn) {
669 for (auto [entry, arg] :
670 llvm::zip(getTargetType().getEntries(), region.getArguments()))
671 setNameFn(arg, entry.name.getValue());
672}
673
674//===----------------------------------------------------------------------===//
675// TargetOp
676//===----------------------------------------------------------------------===//
677
678LogicalResult TargetOp::verifyRegions() {
679 if (!getTarget().entryTypesMatch(
680 getBody()->getTerminator()->getOperandTypes()))
681 return emitOpError("terminator operand types must match dict entry types");
682
683 return success();
684}
685
686//===----------------------------------------------------------------------===//
687// ValidateOp
688//===----------------------------------------------------------------------===//
689
690LogicalResult ValidateOp::verify() {
691 if (!getRef().getType().isValidContentType(getType()))
692 return emitOpError(
693 "result type must be a valid content type for the ref value");
694
695 return success();
696}
697
698//===----------------------------------------------------------------------===//
699// ArrayCreateOp
700//===----------------------------------------------------------------------===//
701
702LogicalResult ArrayCreateOp::verify() {
703 if (!getElements().empty() &&
704 getElements()[0].getType() != getType().getElementType())
705 return emitOpError("operand types must match array element type, expected ")
706 << getType().getElementType() << " but got "
707 << getElements()[0].getType();
708
709 return success();
710}
711
712ParseResult ArrayCreateOp::parse(OpAsmParser &parser, OperationState &result) {
713 SmallVector<OpAsmParser::UnresolvedOperand> operands;
714 Type elementType;
715
716 if (parser.parseOperandList(operands) || parser.parseColon() ||
717 parser.parseType(elementType) ||
718 parser.parseOptionalAttrDict(result.attributes))
719 return failure();
720
721 if (failed(parser.resolveOperands(operands, elementType, result.operands)))
722 return failure();
723
724 result.addTypes(ArrayType::get(elementType));
725
726 return success();
727}
728
729void ArrayCreateOp::print(OpAsmPrinter &p) {
730 p << ' ';
731 p.printOperands(getElements());
732 p << " : " << getType().getElementType();
733 p.printOptionalAttrDict((*this)->getAttrs(), {});
734}
735
736//===----------------------------------------------------------------------===//
737// MemoryBlockDeclareOp
738//===----------------------------------------------------------------------===//
739
740LogicalResult MemoryBlockDeclareOp::verify() {
741 if (getBaseAddress().getBitWidth() != getType().getAddressWidth())
742 return emitOpError(
743 "base address width must match memory block address width");
744
745 if (getEndAddress().getBitWidth() != getType().getAddressWidth())
746 return emitOpError(
747 "end address width must match memory block address width");
748
749 if (getBaseAddress().ugt(getEndAddress()))
750 return emitOpError(
751 "base address must be smaller than or equal to the end address");
752
753 return success();
754}
755
756ParseResult MemoryBlockDeclareOp::parse(OpAsmParser &parser,
757 OperationState &result) {
758 SmallVector<OpAsmParser::UnresolvedOperand> operands;
759 MemoryBlockType memoryBlockType;
760 APInt start, end;
761
762 if (parser.parseLSquare())
763 return failure();
764
765 auto startLoc = parser.getCurrentLocation();
766 if (parser.parseInteger(start))
767 return failure();
768
769 if (parser.parseMinus())
770 return failure();
771
772 auto endLoc = parser.getCurrentLocation();
773 if (parser.parseInteger(end) || parser.parseRSquare() ||
774 parser.parseColonType(memoryBlockType) ||
775 parser.parseOptionalAttrDict(result.attributes))
776 return failure();
777
778 auto width = memoryBlockType.getAddressWidth();
779 auto adjustAPInt = [&](APInt value, llvm::SMLoc loc) -> FailureOr<APInt> {
780 if (value.getBitWidth() > width) {
781 if (!value.isIntN(width))
782 return parser.emitError(
783 loc,
784 "address out of range for memory block with address width ")
785 << width;
786
787 return value.trunc(width);
788 }
789
790 if (value.getBitWidth() < width)
791 return value.zext(width);
792
793 return value;
794 };
795
796 auto startRes = adjustAPInt(start, startLoc);
797 auto endRes = adjustAPInt(end, endLoc);
798 if (failed(startRes) || failed(endRes))
799 return failure();
800
801 auto intType = IntegerType::get(result.getContext(), width);
802 result.addAttribute(getBaseAddressAttrName(result.name),
803 IntegerAttr::get(intType, *startRes));
804 result.addAttribute(getEndAddressAttrName(result.name),
805 IntegerAttr::get(intType, *endRes));
806
807 result.addTypes(memoryBlockType);
808 return success();
809}
810
811void MemoryBlockDeclareOp::print(OpAsmPrinter &p) {
812 SmallVector<char> str;
813 getBaseAddress().toString(str, 16, false, false, false);
814 p << " [0x" << str;
815 p << " - 0x";
816 str.clear();
817 getEndAddress().toString(str, 16, false, false, false);
818 p << str << "] : " << getType();
819 p.printOptionalAttrDict((*this)->getAttrs(),
820 {getBaseAddressAttrName(), getEndAddressAttrName()});
821}
822
823//===----------------------------------------------------------------------===//
824// MemoryBaseAddressOp
825//===----------------------------------------------------------------------===//
826
827LogicalResult MemoryBaseAddressOp::inferReturnTypes(
828 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
829 DictionaryAttr attributes, OpaqueProperties properties, RegionRange regions,
830 SmallVectorImpl<Type> &inferredReturnTypes) {
831 if (operands.empty())
832 return failure();
833 auto memTy = dyn_cast<MemoryType>(operands[0].getType());
834 if (!memTy)
835 return failure();
836 inferredReturnTypes.push_back(
837 ImmediateType::get(context, memTy.getAddressWidth()));
838 return success();
839}
840
841//===----------------------------------------------------------------------===//
842// TableGen generated logic.
843//===----------------------------------------------------------------------===//
844
845#define GET_OP_CLASSES
846#include "circt/Dialect/RTG/IR/RTG.cpp.inc"
assert(baseType &&"element must be base type")
MlirType elementType
Definition CHIRRTL.cpp:29
static size_t getAddressWidth(size_t depth)
static InstancePath empty
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:55
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:110
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
Definition LLVM.h:183
Definition rtg.py:1
Definition seq.py:1