MLIR 24.0.0git
SMTAttributes.cpp
Go to the documentation of this file.
1//===- SMTAttributes.cpp - Implement SMT attributes -----------------------===//
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
12
13using namespace mlir;
14using namespace mlir::smt;
15
16//===----------------------------------------------------------------------===//
17// BitVectorAttr
18//===----------------------------------------------------------------------===//
19
20LogicalResult BitVectorAttr::verify(
22 APInt value) { // NOLINT(performance-unnecessary-value-param)
23 if (value.getBitWidth() < 1)
24 return emitError() << "bit-width must be at least 1, but got "
25 << value.getBitWidth();
26 return success();
27}
28
29std::string BitVectorAttr::getValueAsString(bool prefix) const {
30 unsigned width = getValue().getBitWidth();
31 SmallVector<char> toPrint;
32 StringRef pref = prefix ? "#" : "";
33 if (width % 4 == 0) {
34 getValue().toString(toPrint, 16, false, false, false);
35 // APInt's 'toString' omits leading zeros. However, those are critical here
36 // because they determine the bit-width of the bit-vector.
37 SmallVector<char> leadingZeros(width / 4 - toPrint.size(), '0');
38 return (pref + "x" + Twine(leadingZeros) + toPrint).str();
39 }
40
41 getValue().toString(toPrint, 2, false, false, false);
42 // APInt's 'toString' omits leading zeros
43 SmallVector<char> leadingZeros(width - toPrint.size(), '0');
44 return (pref + "b" + Twine(leadingZeros) + toPrint).str();
45}
46
47/// Parse an SMT-LIB formatted bit-vector string.
48static FailureOr<APInt>
50 StringRef value) {
51 if (value[0] != '#')
52 return emitError() << "expected '#'";
53
54 if (value.size() < 3)
55 return emitError() << "expected at least one digit";
56
57 if (value[1] == 'b')
58 return APInt(value.size() - 2, std::string(value.begin() + 2, value.end()),
59 2);
60
61 if (value[1] == 'x')
62 return APInt((value.size() - 2) * 4,
63 std::string(value.begin() + 2, value.end()), 16);
64
65 return emitError() << "expected either 'b' or 'x'";
66}
67
68BitVectorAttr BitVectorAttr::get(MLIRContext *context, StringRef value) {
69 auto maybeValue = parseBitVectorString(nullptr, value);
70
71 assert(succeeded(maybeValue) && "string must have SMT-LIB format");
72 return Base::get(context, *maybeValue);
73}
74
75BitVectorAttr
76BitVectorAttr::getChecked(function_ref<InFlightDiagnostic()> emitError,
77 MLIRContext *context, StringRef value) {
78 auto maybeValue = parseBitVectorString(emitError, value);
79 if (failed(maybeValue))
80 return {};
81
82 return Base::getChecked(emitError, context, *maybeValue);
83}
84
85BitVectorAttr BitVectorAttr::get(MLIRContext *context, uint64_t value,
86 unsigned width) {
87 return Base::get(context, APInt(width, value));
88}
89
90BitVectorAttr
91BitVectorAttr::getChecked(function_ref<InFlightDiagnostic()> emitError,
92 MLIRContext *context, uint64_t value,
93 unsigned width) {
94 if (width < 64 && value >= (UINT64_C(1) << width)) {
95 emitError() << "value does not fit in a bit-vector of desired width";
96 return {};
97 }
98 return Base::getChecked(emitError, context, APInt(width, value));
99}
100
101Attribute BitVectorAttr::parse(AsmParser &odsParser, Type odsType) {
102 llvm::SMLoc loc = odsParser.getCurrentLocation();
103
104 APInt val;
105 if (odsParser.parseLess() || odsParser.parseInteger(val) ||
106 odsParser.parseGreater())
107 return {};
108
109 // Requires the use of `quantified(<attr>)` in operation assembly formats.
110 if (!odsType || !llvm::isa<BitVectorType>(odsType)) {
111 odsParser.emitError(loc) << "explicit bit-vector type required";
112 return {};
113 }
114
115 unsigned width = llvm::cast<BitVectorType>(odsType).getWidth();
116
117 if (width > val.getBitWidth()) {
118 // sext is always safe here, even for unsigned values, because the
119 // parseOptionalInteger method will return something with a zero in the
120 // top bits if it is a positive number.
121 val = val.sext(width);
122 } else if (width < val.getBitWidth()) {
123 // The parser can return an unnecessarily wide result.
124 // This isn't a problem, but truncating off bits is bad.
125 unsigned neededBits =
126 val.isNegative() ? val.getSignificantBits() : val.getActiveBits();
127 if (width < neededBits) {
128 odsParser.emitError(loc)
129 << "integer value out of range for given bit-vector type " << odsType;
130 return {};
131 }
132 val = val.trunc(width);
133 }
134
135 return BitVectorAttr::get(odsParser.getContext(), val);
136}
137
138void BitVectorAttr::print(AsmPrinter &odsPrinter) const {
139 // This printer only works for the extended format where the MLIR
140 // infrastructure prints the type for us. This means, the attribute should
141 // never be used without `quantified` in an assembly format.
142 odsPrinter << "<" << getValue() << ">";
143}
144
145Type BitVectorAttr::getType() const {
146 return BitVectorType::get(getContext(), getValue().getBitWidth());
147}
148
149//===----------------------------------------------------------------------===//
150// ODS Boilerplate
151//===----------------------------------------------------------------------===//
152
153#define GET_ATTRDEF_CLASSES
154#include "mlir/Dialect/SMT/IR/SMTAttributes.cpp.inc"
155
156void SMTDialect::registerAttributes() {
157 addAttributes<
158#define GET_ATTRDEF_LIST
159#include "mlir/Dialect/SMT/IR/SMTAttributes.cpp.inc"
160 >();
161}
return success()
static unsigned getBitWidth(Type type)
Definition Pattern.cpp:407
b getContext())
static FailureOr< APInt > parseBitVectorString(function_ref< InFlightDiagnostic()> emitError, StringRef value)
Parse an SMT-LIB formatted bit-vector string.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseGreater()=0
Parse a '>' token.
This base class exposes generic asm printer hooks, usable across the various derived printers.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:853
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155