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/Support/FormatVariadic.h"
13 
14 using namespace mlir;
15 using namespace test;
16 
17 namespace {
18 struct TestElementsAttrInterface
19     : public PassWrapper<TestElementsAttrInterface, OperationPass<ModuleOp>> {
20   MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestElementsAttrInterface)
21 
22   StringRef getArgument() const final { return "test-elements-attr-interface"; }
23   StringRef getDescription() const final {
24     return "Test ElementsAttr interface support.";
25   }
26   void runOnOperation() override {
27     getOperation().walk([&](Operation *op) {
28       for (NamedAttribute attr : op->getAttrs()) {
29         auto elementsAttr = attr.getValue().dyn_cast<ElementsAttr>();
30         if (!elementsAttr)
31           continue;
32         testElementsAttrIteration<uint64_t>(op, elementsAttr, "uint64_t");
33         testElementsAttrIteration<APInt>(op, elementsAttr, "APInt");
34         testElementsAttrIteration<IntegerAttr>(op, elementsAttr, "IntegerAttr");
35       }
36     });
37   }
38 
39   template <typename T>
40   void testElementsAttrIteration(Operation *op, ElementsAttr attr,
41                                  StringRef type) {
42     InFlightDiagnostic diag = op->emitError()
43                               << "Test iterating `" << type << "`: ";
44 
45     auto values = attr.tryGetValues<T>();
46     if (!values) {
47       diag << "unable to iterate type";
48       return;
49     }
50 
51     llvm::interleaveComma(*values, diag, [&](T value) {
52       diag << llvm::formatv("{0}", value).str();
53     });
54   }
55 };
56 } // namespace
57 
58 namespace mlir {
59 namespace test {
60 void registerTestBuiltinAttributeInterfaces() {
61   PassRegistration<TestElementsAttrInterface>();
62 }
63 } // namespace test
64 } // namespace mlir
65