1//===- TestBuiltinAttributeInterfaces.cpp ---------------------------------===//
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#include <utility>
10
11#include "TestAttributes.h"
12#include "mlir/IR/BuiltinOps.h"
13#include "mlir/Pass/Pass.h"
14#include "llvm/ADT/TypeSwitch.h"
15#include "llvm/Support/FormatVariadic.h"
16
17using namespace mlir;
18using namespace test;
19
20// Helper to print one scalar value, force int8_t to print as integer instead of
21// char.
22template <typename T>
23static void printOneElement(InFlightDiagnostic &os, T value) {
24 os << llvm::formatv("{0}", value).str();
25}
26
27namespace {
28struct TestElementsAttrInterface
29 : public PassWrapper<TestElementsAttrInterface, OperationPass<ModuleOp>> {
30 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestElementsAttrInterface)
31
32 StringRef getArgument() const final { return "test-elements-attr-interface"; }
33 StringRef getDescription() const final {
34 return "Test ElementsAttr interface support.";
35 }
36 void runOnOperation() override {
37 getOperation().walk(callback: [&](Operation *op) {
38 NamedAttrList attrs(op->getDiscardableAttrDictionary());
39 if (op->getPropertiesStorageSize())
40 op->getName().walkInherentAttrs(
41 op,
42 visitor: [&](StringRef name, Attribute &attr) { attrs.append(name, attr); });
43 for (NamedAttribute attr : attrs) {
44 auto elementsAttr = dyn_cast<ElementsAttr>(Val: attr.getValue());
45 if (!elementsAttr)
46 continue;
47 testElementsAttrIteration<int64_t>(op, attr: elementsAttr, type: "int64_t");
48 testElementsAttrIteration<uint64_t>(op, attr: elementsAttr, type: "uint64_t");
49 testElementsAttrIteration<APInt>(op, attr: elementsAttr, type: "APInt");
50 testElementsAttrIteration<IntegerAttr>(op, attr: elementsAttr, type: "IntegerAttr");
51 }
52 });
53 }
54
55 template <typename T>
56 void testElementsAttrIteration(Operation *op, ElementsAttr attr,
57 StringRef type) {
58 InFlightDiagnostic diag = op->emitError()
59 << "Test iterating `" << type << "`: ";
60
61 if (!isa<mlir::IntegerType>(Val: attr.getElementType())) {
62 diag << "expected element type to be an integer type";
63 return;
64 }
65
66 auto values = attr.tryGetValues<T>();
67 if (!values) {
68 diag << "unable to iterate type";
69 return;
70 }
71
72 llvm::interleaveComma(*values, diag, [&](T value) {
73 printOneElement(diag, std::move(value));
74 });
75 }
76};
77} // namespace
78
79namespace mlir {
80namespace test {
81void registerTestBuiltinAttributeInterfaces() {
82 PassRegistration<TestElementsAttrInterface>();
83}
84} // namespace test
85} // namespace mlir
86