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