1//===- ODSSupport.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// This file contains out-of-line implementations of the support types that
10// Operation and related classes build on top of.
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/IR/ODSSupport.h"
15#include "mlir/IR/BuiltinAttributes.h"
16#include "mlir/IR/BuiltinTypes.h"
17#include "mlir/IR/Diagnostics.h"
18
19using namespace mlir;
20
21LogicalResult
22mlir::convertFromAttribute(int64_t &storage, Attribute attr,
23 function_ref<InFlightDiagnostic()> emitError) {
24 auto valueAttr = dyn_cast<IntegerAttr>(attr);
25 if (!valueAttr) {
26 emitError() << "expected IntegerAttr for key `value`";
27 return failure();
28 }
29 storage = valueAttr.getValue().getSExtValue();
30 return success();
31}
32Attribute mlir::convertToAttribute(MLIRContext *ctx, int64_t storage) {
33 return IntegerAttr::get(IntegerType::get(ctx, 64), storage);
34}
35
36template <typename DenseArrayTy, typename T>
37LogicalResult
38convertDenseArrayFromAttr(MutableArrayRef<T> storage, Attribute attr,
39 function_ref<InFlightDiagnostic()> emitError,
40 StringRef denseArrayTyStr) {
41 auto valueAttr = dyn_cast<DenseArrayTy>(attr);
42 if (!valueAttr) {
43 emitError() << "expected " << denseArrayTyStr << " for key `value`";
44 return failure();
45 }
46 if (valueAttr.size() != static_cast<int64_t>(storage.size())) {
47 emitError() << "size mismatch in attribute conversion: " << valueAttr.size()
48 << " vs " << storage.size();
49 return failure();
50 }
51 llvm::copy(valueAttr.asArrayRef(), storage.begin());
52 return success();
53}
54LogicalResult
55mlir::convertFromAttribute(MutableArrayRef<int64_t> storage, Attribute attr,
56 function_ref<InFlightDiagnostic()> emitError) {
57 return convertDenseArrayFromAttr<DenseI64ArrayAttr>(storage, attr, emitError,
58 denseArrayTyStr: "DenseI64ArrayAttr");
59}
60LogicalResult
61mlir::convertFromAttribute(MutableArrayRef<int32_t> storage, Attribute attr,
62 function_ref<InFlightDiagnostic()> emitError) {
63 return convertDenseArrayFromAttr<DenseI32ArrayAttr>(storage, attr, emitError,
64 denseArrayTyStr: "DenseI32ArrayAttr");
65}
66
67Attribute mlir::convertToAttribute(MLIRContext *ctx,
68 ArrayRef<int64_t> storage) {
69 return DenseI64ArrayAttr::get(ctx, storage);
70}
71

source code of mlir/lib/IR/ODSSupport.cpp