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