2018-06-23 16:03:42 -07:00
|
|
|
//===- AsmPrinter.cpp - MLIR Assembly Printer Implementation --------------===//
|
|
|
|
//
|
2020-01-26 03:58:30 +00:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
2019-12-23 09:35:36 -08:00
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2018-06-23 16:03:42 -07:00
|
|
|
//
|
2019-12-23 09:35:36 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2018-06-23 16:03:42 -07:00
|
|
|
//
|
|
|
|
// This file implements the MLIR AsmPrinter class, which is used to implement
|
|
|
|
// the various print() methods on the core IR objects.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2018-06-29 18:09:29 -07:00
|
|
|
#include "mlir/IR/AffineExpr.h"
|
|
|
|
#include "mlir/IR/AffineMap.h"
|
2020-01-14 15:23:05 -08:00
|
|
|
#include "mlir/IR/AsmState.h"
|
2018-07-04 20:45:39 -07:00
|
|
|
#include "mlir/IR/Attributes.h"
|
2021-09-29 22:05:44 -07:00
|
|
|
#include "mlir/IR/Builders.h"
|
2023-12-08 11:34:44 -08:00
|
|
|
#include "mlir/IR/BuiltinAttributes.h"
|
2021-11-02 05:51:38 +00:00
|
|
|
#include "mlir/IR/BuiltinDialect.h"
|
2023-12-08 11:34:44 -08:00
|
|
|
#include "mlir/IR/BuiltinTypeInterfaces.h"
|
2020-12-03 17:22:29 -08:00
|
|
|
#include "mlir/IR/BuiltinTypes.h"
|
2019-03-01 16:58:00 -08:00
|
|
|
#include "mlir/IR/Dialect.h"
|
2019-11-01 14:47:42 -07:00
|
|
|
#include "mlir/IR/DialectImplementation.h"
|
[mlir] Add a new builtin DenseResourceElementsAttr
This attributes is intended cover the current set of use cases that abuse
DenseElementsAttr, e.g. when the data is large. Using resources for large
data is one of the major reasons why they were added; e.g. they can be
deallocated mid-compilation, they support a wide variety of data origins
(e.g, heap allocated, mmap'd, etc.), they can support mutation, etc.
I considered at length not having a builtin variant of this, and instead
having multiple versions of this attribute for dialects that are interested,
but they all boiled down to the exact same attribute definition. Given the
generality of this attribute, it feels more aligned to keep it next to DenseArrayAttr
(given that DenseArrayAttr covers the "small" case, and DenseResourcesElementsAttr
covers the "large" case). The underlying infra used to build this attribute is
general, and having a builtin attribute doesn't preclude users from defining
their own when it makes sense (they can even share a blob manager with the
builtin dialect to avoid data duplication).
Differential Revision: https://reviews.llvm.org/D130022
2022-07-19 18:22:55 -07:00
|
|
|
#include "mlir/IR/DialectResourceBlobManager.h"
|
2018-08-07 14:24:38 -07:00
|
|
|
#include "mlir/IR/IntegerSet.h"
|
2019-01-10 22:08:39 -08:00
|
|
|
#include "mlir/IR/MLIRContext.h"
|
2018-07-24 16:07:22 -07:00
|
|
|
#include "mlir/IR/OpImplementation.h"
|
2019-03-26 14:45:38 -07:00
|
|
|
#include "mlir/IR/Operation.h"
|
2022-03-07 07:49:46 -08:00
|
|
|
#include "mlir/IR/Verifier.h"
|
2018-08-15 09:09:54 -07:00
|
|
|
#include "llvm/ADT/APFloat.h"
|
2023-12-08 11:34:44 -08:00
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
2018-06-23 16:03:42 -07:00
|
|
|
#include "llvm/ADT/DenseMap.h"
|
2019-05-06 10:36:32 -07:00
|
|
|
#include "llvm/ADT/MapVector.h"
|
2018-11-12 14:58:53 -08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2021-08-28 03:03:49 +00:00
|
|
|
#include "llvm/ADT/ScopeExit.h"
|
2019-07-09 10:40:29 -07:00
|
|
|
#include "llvm/ADT/ScopedHashTable.h"
|
2019-01-10 22:08:39 -08:00
|
|
|
#include "llvm/ADT/SetVector.h"
|
2018-08-01 10:43:18 -07:00
|
|
|
#include "llvm/ADT/SmallString.h"
|
|
|
|
#include "llvm/ADT/StringExtras.h"
|
|
|
|
#include "llvm/ADT/StringSet.h"
|
2020-08-07 13:30:29 -07:00
|
|
|
#include "llvm/ADT/TypeSwitch.h"
|
2019-01-23 13:11:23 -08:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2022-05-10 22:48:46 +00:00
|
|
|
#include "llvm/Support/Debug.h"
|
2021-04-21 10:48:54 -04:00
|
|
|
#include "llvm/Support/Endian.h"
|
2024-06-21 16:09:54 +02:00
|
|
|
#include "llvm/Support/ManagedStatic.h"
|
2019-01-10 22:08:39 -08:00
|
|
|
#include "llvm/Support/Regex.h"
|
2020-01-09 12:39:26 -08:00
|
|
|
#include "llvm/Support/SaveAndRestore.h"
|
2022-03-07 07:49:46 -08:00
|
|
|
#include "llvm/Support/Threading.h"
|
2023-08-23 16:54:18 +00:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2023-12-08 11:34:44 -08:00
|
|
|
#include <type_traits>
|
2021-05-12 11:21:25 +08:00
|
|
|
|
2023-01-13 21:05:06 -08:00
|
|
|
#include <optional>
|
2023-05-07 18:19:46 -05:00
|
|
|
#include <tuple>
|
2021-05-12 11:21:25 +08:00
|
|
|
|
2018-06-23 16:03:42 -07:00
|
|
|
using namespace mlir;
|
2020-01-14 15:23:05 -08:00
|
|
|
using namespace mlir::detail;
|
2018-06-23 16:03:42 -07:00
|
|
|
|
2022-05-10 22:48:46 +00:00
|
|
|
#define DEBUG_TYPE "mlir-asm-printer"
|
|
|
|
|
2018-10-09 22:08:52 -07:00
|
|
|
void OperationName::print(raw_ostream &os) const { os << getStringRef(); }
|
|
|
|
|
|
|
|
void OperationName::dump() const { print(llvm::errs()); }
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
// AsmParser
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
2021-12-22 00:19:53 +00:00
|
|
|
AsmParser::~AsmParser() = default;
|
|
|
|
DialectAsmParser::~DialectAsmParser() = default;
|
|
|
|
OpAsmParser::~OpAsmParser() = default;
|
2021-09-24 19:56:01 +00:00
|
|
|
|
2021-09-29 22:05:44 -07:00
|
|
|
MLIRContext *AsmParser::getContext() const { return getBuilder().getContext(); }
|
|
|
|
|
2023-09-26 20:03:01 -07:00
|
|
|
/// Parse a type list.
|
2024-12-17 07:59:11 -08:00
|
|
|
/// This is out-of-line to work-around
|
|
|
|
/// https://github.com/llvm/llvm-project/issues/62918
|
2023-09-26 20:03:01 -07:00
|
|
|
ParseResult AsmParser::parseTypeList(SmallVectorImpl<Type> &result) {
|
2024-02-08 17:50:41 -08:00
|
|
|
return parseCommaSeparatedList(
|
|
|
|
[&]() { return parseType(result.emplace_back()); });
|
|
|
|
}
|
2023-09-26 20:03:01 -07:00
|
|
|
|
2021-09-29 22:05:44 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2021-09-24 19:56:01 +00:00
|
|
|
// DialectAsmPrinter
|
2021-09-29 22:05:44 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2021-09-24 19:56:01 +00:00
|
|
|
|
2021-12-22 00:19:53 +00:00
|
|
|
DialectAsmPrinter::~DialectAsmPrinter() = default;
|
2019-11-01 14:47:42 -07:00
|
|
|
|
2021-09-29 22:05:44 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2020-12-29 11:05:45 -08:00
|
|
|
// OpAsmPrinter
|
2021-09-29 22:05:44 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2020-12-29 11:05:45 -08:00
|
|
|
|
2021-12-22 00:19:53 +00:00
|
|
|
OpAsmPrinter::~OpAsmPrinter() = default;
|
2018-07-24 16:07:22 -07:00
|
|
|
|
2020-12-29 11:05:45 -08:00
|
|
|
void OpAsmPrinter::printFunctionalType(Operation *op) {
|
|
|
|
auto &os = getStream();
|
|
|
|
os << '(';
|
2021-01-06 17:38:37 -08:00
|
|
|
llvm::interleaveComma(op->getOperands(), os, [&](Value operand) {
|
2020-12-29 11:05:45 -08:00
|
|
|
// Print the types of null values as <<NULL TYPE>>.
|
2021-01-06 17:38:37 -08:00
|
|
|
*this << (operand ? operand.getType() : Type());
|
2020-12-29 11:05:45 -08:00
|
|
|
});
|
|
|
|
os << ") -> ";
|
|
|
|
|
|
|
|
// Print the result list. We don't parenthesize single result types unless
|
|
|
|
// it is a function (avoiding a grammar ambiguity).
|
2021-01-06 17:38:37 -08:00
|
|
|
bool wrapped = op->getNumResults() != 1;
|
2020-12-29 11:05:45 -08:00
|
|
|
if (!wrapped && op->getResult(0).getType() &&
|
2023-05-11 11:10:46 +02:00
|
|
|
llvm::isa<FunctionType>(op->getResult(0).getType()))
|
2020-12-29 11:05:45 -08:00
|
|
|
wrapped = true;
|
|
|
|
|
|
|
|
if (wrapped)
|
|
|
|
os << '(';
|
|
|
|
|
2021-01-06 17:38:37 -08:00
|
|
|
llvm::interleaveComma(op->getResults(), os, [&](const OpResult &result) {
|
2020-12-29 11:05:45 -08:00
|
|
|
// Print the types of null values as <<NULL TYPE>>.
|
2021-01-06 17:38:37 -08:00
|
|
|
*this << (result ? result.getType() : Type());
|
2020-12-29 11:05:45 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
if (wrapped)
|
|
|
|
os << ')';
|
|
|
|
}
|
|
|
|
|
2021-09-29 22:05:44 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-11-20 10:19:01 -08:00
|
|
|
// Operation OpAsm interface.
|
2021-09-29 22:05:44 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-11-20 10:19:01 -08:00
|
|
|
|
|
|
|
/// The OpAsmOpInterface, see OpAsmInterface.td for more details.
|
2025-02-19 02:18:59 +08:00
|
|
|
#include "mlir/IR/OpAsmAttrInterface.cpp.inc"
|
2025-01-28 13:31:41 +08:00
|
|
|
#include "mlir/IR/OpAsmOpInterface.cpp.inc"
|
|
|
|
#include "mlir/IR/OpAsmTypeInterface.cpp.inc"
|
2019-11-20 10:19:01 -08:00
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
LogicalResult
|
|
|
|
OpAsmDialectInterface::parseResource(AsmParsedResourceEntry &entry) const {
|
|
|
|
return entry.emitError() << "unknown 'resource' key '" << entry.getKey()
|
|
|
|
<< "' for dialect '" << getDialect()->getNamespace()
|
|
|
|
<< "'";
|
|
|
|
}
|
|
|
|
|
2018-07-17 16:56:54 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-10-07 13:54:16 -07:00
|
|
|
// OpPrintingFlags
|
2018-07-17 16:56:54 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2020-04-11 23:11:51 -07:00
|
|
|
namespace {
|
|
|
|
/// This struct contains command line options that can be used to initialize
|
|
|
|
/// various bits of the AsmPrinter. This uses a struct wrapper to avoid the need
|
|
|
|
/// for global command line options.
|
|
|
|
struct AsmPrinterOptions {
|
|
|
|
llvm::cl::opt<int64_t> printElementsAttrWithHexIfLarger{
|
|
|
|
"mlir-print-elementsattrs-with-hex-if-larger",
|
|
|
|
llvm::cl::desc(
|
|
|
|
"Print DenseElementsAttrs with a hex string that have "
|
|
|
|
"more elements than the given upper limit (use -1 to disable)")};
|
|
|
|
|
|
|
|
llvm::cl::opt<unsigned> elideElementsAttrIfLarger{
|
|
|
|
"mlir-elide-elementsattrs-if-larger",
|
|
|
|
llvm::cl::desc("Elide ElementsAttrs with \"...\" that have "
|
|
|
|
"more elements than the given upper limit")};
|
|
|
|
|
2023-08-23 16:54:18 +00:00
|
|
|
llvm::cl::opt<unsigned> elideResourceStringsIfLarger{
|
|
|
|
"mlir-elide-resource-strings-if-larger",
|
|
|
|
llvm::cl::desc(
|
|
|
|
"Elide printing value of resources if string is too long in chars.")};
|
|
|
|
|
2020-04-11 23:11:51 -07:00
|
|
|
llvm::cl::opt<bool> printDebugInfoOpt{
|
|
|
|
"mlir-print-debuginfo", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Print debug info in MLIR output")};
|
|
|
|
|
|
|
|
llvm::cl::opt<bool> printPrettyDebugInfoOpt{
|
|
|
|
"mlir-pretty-debuginfo", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Print pretty debug info in MLIR output")};
|
|
|
|
|
|
|
|
// Use the generic op output form in the operation printer even if the custom
|
|
|
|
// form is defined.
|
|
|
|
llvm::cl::opt<bool> printGenericOpFormOpt{
|
|
|
|
"mlir-print-op-generic", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Print the generic op form"), llvm::cl::Hidden};
|
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
llvm::cl::opt<bool> assumeVerifiedOpt{
|
|
|
|
"mlir-print-assume-verified", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Skip op verification when using custom printers"),
|
|
|
|
llvm::cl::Hidden};
|
|
|
|
|
2020-04-11 23:11:51 -07:00
|
|
|
llvm::cl::opt<bool> printLocalScopeOpt{
|
|
|
|
"mlir-print-local-scope", llvm::cl::init(false),
|
2022-01-23 07:39:01 +05:30
|
|
|
llvm::cl::desc("Print with local scope and inline information (eliding "
|
2025-02-13 10:43:37 +01:00
|
|
|
"aliases for attributes, types, and locations)")};
|
2022-04-22 18:52:54 +00:00
|
|
|
|
2024-01-11 17:52:41 -05:00
|
|
|
llvm::cl::opt<bool> skipRegionsOpt{
|
|
|
|
"mlir-print-skip-regions", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Skip regions when printing ops.")};
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
llvm::cl::opt<bool> printValueUsers{
|
|
|
|
"mlir-print-value-users", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc(
|
|
|
|
"Print users of operation results and block arguments as a comment")};
|
2024-05-07 10:45:28 -05:00
|
|
|
|
|
|
|
llvm::cl::opt<bool> printUniqueSSAIDs{
|
|
|
|
"mlir-print-unique-ssa-ids", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Print unique SSA ID numbers for values, block arguments "
|
|
|
|
"and naming conflicts across all regions")};
|
2024-12-17 07:59:11 -08:00
|
|
|
|
|
|
|
llvm::cl::opt<bool> useNameLocAsPrefix{
|
|
|
|
"mlir-use-nameloc-as-prefix", llvm::cl::init(false),
|
|
|
|
llvm::cl::desc("Print SSA IDs using NameLocs as prefixes")};
|
2020-04-11 23:11:51 -07:00
|
|
|
};
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace
|
2020-04-11 23:11:51 -07:00
|
|
|
|
|
|
|
static llvm::ManagedStatic<AsmPrinterOptions> clOptions;
|
|
|
|
|
|
|
|
/// Register a set of useful command-line options that can be used to configure
|
|
|
|
/// various flags within the AsmPrinter.
|
|
|
|
void mlir::registerAsmPrinterCLOptions() {
|
|
|
|
// Make sure that the options struct has been initialized.
|
|
|
|
*clOptions;
|
|
|
|
}
|
2019-11-13 14:21:16 -08:00
|
|
|
|
2019-10-07 13:54:16 -07:00
|
|
|
/// Initialize the printing flags with default supplied by the cl::opts above.
|
|
|
|
OpPrintingFlags::OpPrintingFlags()
|
2020-04-11 23:11:51 -07:00
|
|
|
: printDebugInfoFlag(false), printDebugInfoPrettyFormFlag(false),
|
2023-03-13 14:33:31 +01:00
|
|
|
printGenericOpFormFlag(false), skipRegionsFlag(false),
|
|
|
|
assumeVerifiedFlag(false), printLocalScope(false),
|
2024-12-17 07:59:11 -08:00
|
|
|
printValueUsersFlag(false), printUniqueSSAIDsFlag(false),
|
|
|
|
useNameLocAsPrefix(false) {
|
2020-04-11 23:11:51 -07:00
|
|
|
// Initialize based upon command line options, if they are available.
|
|
|
|
if (!clOptions.isConstructed())
|
|
|
|
return;
|
|
|
|
if (clOptions->elideElementsAttrIfLarger.getNumOccurrences())
|
|
|
|
elementsAttrElementLimit = clOptions->elideElementsAttrIfLarger;
|
2024-04-09 03:08:32 +03:00
|
|
|
if (clOptions->printElementsAttrWithHexIfLarger.getNumOccurrences())
|
|
|
|
elementsAttrHexElementLimit =
|
|
|
|
clOptions->printElementsAttrWithHexIfLarger.getValue();
|
2023-08-23 16:54:18 +00:00
|
|
|
if (clOptions->elideResourceStringsIfLarger.getNumOccurrences())
|
|
|
|
resourceStringCharLimit = clOptions->elideResourceStringsIfLarger;
|
2020-04-11 23:11:51 -07:00
|
|
|
printDebugInfoFlag = clOptions->printDebugInfoOpt;
|
|
|
|
printDebugInfoPrettyFormFlag = clOptions->printPrettyDebugInfoOpt;
|
|
|
|
printGenericOpFormFlag = clOptions->printGenericOpFormOpt;
|
2022-03-07 07:49:46 -08:00
|
|
|
assumeVerifiedFlag = clOptions->assumeVerifiedOpt;
|
2020-04-11 23:11:51 -07:00
|
|
|
printLocalScope = clOptions->printLocalScopeOpt;
|
2024-01-11 17:52:41 -05:00
|
|
|
skipRegionsFlag = clOptions->skipRegionsOpt;
|
2022-04-22 18:52:54 +00:00
|
|
|
printValueUsersFlag = clOptions->printValueUsers;
|
2024-05-07 10:45:28 -05:00
|
|
|
printUniqueSSAIDsFlag = clOptions->printUniqueSSAIDs;
|
2024-12-17 07:59:11 -08:00
|
|
|
useNameLocAsPrefix = clOptions->useNameLocAsPrefix;
|
2020-04-11 23:11:51 -07:00
|
|
|
}
|
2019-10-07 13:54:16 -07:00
|
|
|
|
2019-10-07 17:18:54 -07:00
|
|
|
/// Enable the elision of large elements attributes, by printing a '...'
|
|
|
|
/// instead of the element data, when the number of elements is greater than
|
|
|
|
/// `largeElementLimit`. Note: The IR generated with this option is not
|
|
|
|
/// parsable.
|
|
|
|
OpPrintingFlags &
|
|
|
|
OpPrintingFlags::elideLargeElementsAttrs(int64_t largeElementLimit) {
|
|
|
|
elementsAttrElementLimit = largeElementLimit;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2024-04-09 03:08:32 +03:00
|
|
|
OpPrintingFlags &
|
|
|
|
OpPrintingFlags::printLargeElementsAttrWithHex(int64_t largeElementLimit) {
|
|
|
|
elementsAttrHexElementLimit = largeElementLimit;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2023-11-09 16:28:58 -08:00
|
|
|
OpPrintingFlags &
|
|
|
|
OpPrintingFlags::elideLargeResourceString(int64_t largeResourceLimit) {
|
|
|
|
resourceStringCharLimit = largeResourceLimit;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2019-10-07 13:54:16 -07:00
|
|
|
/// Enable printing of debug information. If 'prettyForm' is set to true,
|
|
|
|
/// debug information is printed in a more readable 'pretty' form.
|
2022-11-17 20:44:27 -08:00
|
|
|
OpPrintingFlags &OpPrintingFlags::enableDebugInfo(bool enable,
|
|
|
|
bool prettyForm) {
|
|
|
|
printDebugInfoFlag = enable;
|
2019-10-07 13:54:16 -07:00
|
|
|
printDebugInfoPrettyFormFlag = prettyForm;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Always print operations in the generic form.
|
2023-05-23 03:04:21 -07:00
|
|
|
OpPrintingFlags &OpPrintingFlags::printGenericOpForm(bool enable) {
|
|
|
|
printGenericOpFormFlag = enable;
|
2019-10-07 13:54:16 -07:00
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2023-03-13 14:33:31 +01:00
|
|
|
/// Always skip Regions.
|
2023-02-15 15:56:08 -08:00
|
|
|
OpPrintingFlags &OpPrintingFlags::skipRegions(bool skip) {
|
|
|
|
skipRegionsFlag = skip;
|
2023-03-13 14:33:31 +01:00
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
/// Do not verify the operation when using custom operation printers.
|
2025-01-07 12:14:35 +01:00
|
|
|
OpPrintingFlags &OpPrintingFlags::assumeVerified(bool enable) {
|
|
|
|
assumeVerifiedFlag = enable;
|
2022-03-07 07:49:46 -08:00
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2019-11-12 09:36:40 -08:00
|
|
|
/// Use local scope when printing the operation. This allows for using the
|
|
|
|
/// printer in a more localized and thread-safe setting, but may not necessarily
|
|
|
|
/// be identical of what the IR will look like when dumping the full module.
|
2025-01-07 12:14:35 +01:00
|
|
|
OpPrintingFlags &OpPrintingFlags::useLocalScope(bool enable) {
|
|
|
|
printLocalScope = enable;
|
2019-11-12 09:36:40 -08:00
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// Print users of values as comments.
|
2025-01-07 12:14:35 +01:00
|
|
|
OpPrintingFlags &OpPrintingFlags::printValueUsers(bool enable) {
|
|
|
|
printValueUsersFlag = enable;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Print unique SSA ID numbers for values, block arguments and naming conflicts
|
|
|
|
/// across all regions
|
|
|
|
OpPrintingFlags &OpPrintingFlags::printUniqueSSAIDs(bool enable) {
|
|
|
|
printUniqueSSAIDsFlag = enable;
|
2022-04-22 18:52:54 +00:00
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2019-10-07 17:18:54 -07:00
|
|
|
/// Return if the given ElementsAttr should be elided.
|
|
|
|
bool OpPrintingFlags::shouldElideElementsAttr(ElementsAttr attr) const {
|
2022-06-20 20:05:16 -07:00
|
|
|
return elementsAttrElementLimit &&
|
2020-11-26 11:03:12 +00:00
|
|
|
*elementsAttrElementLimit < int64_t(attr.getNumElements()) &&
|
2023-05-11 11:10:46 +02:00
|
|
|
!llvm::isa<SplatElementsAttr>(attr);
|
2019-10-07 17:18:54 -07:00
|
|
|
}
|
|
|
|
|
2024-04-09 03:08:32 +03:00
|
|
|
/// Return if the given ElementsAttr should be printed as hex string.
|
|
|
|
bool OpPrintingFlags::shouldPrintElementsAttrWithHex(ElementsAttr attr) const {
|
|
|
|
// -1 is used to disable hex printing.
|
|
|
|
return (elementsAttrHexElementLimit != -1) &&
|
|
|
|
(elementsAttrHexElementLimit < int64_t(attr.getNumElements())) &&
|
|
|
|
!llvm::isa<SplatElementsAttr>(attr);
|
|
|
|
}
|
|
|
|
|
2025-03-03 14:55:36 -08:00
|
|
|
OpPrintingFlags &OpPrintingFlags::printNameLocAsPrefix(bool enable) {
|
|
|
|
useNameLocAsPrefix = enable;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2020-04-08 12:57:02 -07:00
|
|
|
/// Return the size limit for printing large ElementsAttr.
|
2023-01-14 01:25:58 -08:00
|
|
|
std::optional<int64_t> OpPrintingFlags::getLargeElementsAttrLimit() const {
|
2020-04-08 12:57:02 -07:00
|
|
|
return elementsAttrElementLimit;
|
|
|
|
}
|
|
|
|
|
2024-04-09 03:08:32 +03:00
|
|
|
/// Return the size limit for printing large ElementsAttr as hex string.
|
|
|
|
int64_t OpPrintingFlags::getLargeElementsAttrHexLimit() const {
|
|
|
|
return elementsAttrHexElementLimit;
|
|
|
|
}
|
|
|
|
|
2023-08-23 16:54:18 +00:00
|
|
|
/// Return the size limit for printing large ElementsAttr.
|
|
|
|
std::optional<uint64_t> OpPrintingFlags::getLargeResourceStringLimit() const {
|
|
|
|
return resourceStringCharLimit;
|
|
|
|
}
|
|
|
|
|
2019-10-07 13:54:16 -07:00
|
|
|
/// Return if debug information should be printed.
|
|
|
|
bool OpPrintingFlags::shouldPrintDebugInfo() const {
|
|
|
|
return printDebugInfoFlag;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return if debug information should be printed in the pretty form.
|
|
|
|
bool OpPrintingFlags::shouldPrintDebugInfoPrettyForm() const {
|
|
|
|
return printDebugInfoPrettyFormFlag;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return if operations should be printed in the generic form.
|
|
|
|
bool OpPrintingFlags::shouldPrintGenericOpForm() const {
|
|
|
|
return printGenericOpFormFlag;
|
|
|
|
}
|
|
|
|
|
2023-03-13 14:33:31 +01:00
|
|
|
/// Return if Region should be skipped.
|
|
|
|
bool OpPrintingFlags::shouldSkipRegions() const { return skipRegionsFlag; }
|
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
/// Return if operation verification should be skipped.
|
|
|
|
bool OpPrintingFlags::shouldAssumeVerified() const {
|
|
|
|
return assumeVerifiedFlag;
|
|
|
|
}
|
|
|
|
|
2019-11-12 09:36:40 -08:00
|
|
|
/// Return if the printer should use local scope when dumping the IR.
|
|
|
|
bool OpPrintingFlags::shouldUseLocalScope() const { return printLocalScope; }
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// Return if the printer should print users of values.
|
|
|
|
bool OpPrintingFlags::shouldPrintValueUsers() const {
|
|
|
|
return printValueUsersFlag;
|
|
|
|
}
|
|
|
|
|
2024-05-07 10:45:28 -05:00
|
|
|
/// Return if the printer should use unique IDs.
|
|
|
|
bool OpPrintingFlags::shouldPrintUniqueSSAIDs() const {
|
|
|
|
return printUniqueSSAIDsFlag || shouldPrintGenericOpForm();
|
|
|
|
}
|
|
|
|
|
2024-12-17 07:59:11 -08:00
|
|
|
/// Return if the printer should use NameLocs as prefixes when printing SSA IDs.
|
|
|
|
bool OpPrintingFlags::shouldUseNameLocAsPrefix() const {
|
|
|
|
return useNameLocAsPrefix;
|
|
|
|
}
|
|
|
|
|
2020-02-08 15:01:34 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// NewLineCounter
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
/// This class is a simple formatter that emits a new line when inputted into a
|
|
|
|
/// stream, that enables counting the number of newlines emitted. This class
|
|
|
|
/// should be used whenever emitting newlines in the printer.
|
|
|
|
struct NewLineCounter {
|
|
|
|
unsigned curLine = 1;
|
|
|
|
};
|
|
|
|
|
|
|
|
static raw_ostream &operator<<(raw_ostream &os, NewLineCounter &newLine) {
|
|
|
|
++newLine.curLine;
|
|
|
|
return os << '\n';
|
|
|
|
}
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace
|
2020-02-08 15:01:34 -08:00
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// AsmPrinter::Impl
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace mlir {
|
|
|
|
class AsmPrinter::Impl {
|
|
|
|
public:
|
|
|
|
Impl(raw_ostream &os, AsmStateImpl &state);
|
|
|
|
explicit Impl(Impl &other) : Impl(other.os, other.state) {}
|
|
|
|
|
|
|
|
/// Returns the output stream of the printer.
|
|
|
|
raw_ostream &getStream() { return os; }
|
|
|
|
|
|
|
|
template <typename Container, typename UnaryFunctor>
|
|
|
|
inline void interleaveComma(const Container &c, UnaryFunctor eachFn) const {
|
|
|
|
llvm::interleaveComma(c, os, eachFn);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This enum describes the different kinds of elision for the type of an
|
|
|
|
/// attribute when printing it.
|
|
|
|
enum class AttrTypeElision {
|
|
|
|
/// The type must not be elided,
|
|
|
|
Never,
|
|
|
|
/// The type may be elided when it matches the default used in the parser
|
|
|
|
/// (for example i64 is the default for integer attributes).
|
|
|
|
May,
|
|
|
|
/// The type must be elided.
|
|
|
|
Must
|
|
|
|
};
|
|
|
|
|
|
|
|
/// Print the given attribute or an alias.
|
|
|
|
void printAttribute(Attribute attr,
|
|
|
|
AttrTypeElision typeElision = AttrTypeElision::Never);
|
|
|
|
/// Print the given attribute without considering an alias.
|
|
|
|
void printAttributeImpl(Attribute attr,
|
|
|
|
AttrTypeElision typeElision = AttrTypeElision::Never);
|
|
|
|
|
|
|
|
/// Print the alias for the given attribute, return failure if no alias could
|
|
|
|
/// be printed.
|
|
|
|
LogicalResult printAlias(Attribute attr);
|
|
|
|
|
|
|
|
/// Print the given type or an alias.
|
|
|
|
void printType(Type type);
|
|
|
|
/// Print the given type.
|
|
|
|
void printTypeImpl(Type type);
|
|
|
|
|
|
|
|
/// Print the alias for the given type, return failure if no alias could
|
|
|
|
/// be printed.
|
|
|
|
LogicalResult printAlias(Type type);
|
|
|
|
|
|
|
|
/// Print the given location to the stream. If `allowAlias` is true, this
|
|
|
|
/// allows for the internal location to use an attribute alias.
|
|
|
|
void printLocation(LocationAttr loc, bool allowAlias = false);
|
|
|
|
|
|
|
|
/// Print a reference to the given resource that is owned by the given
|
|
|
|
/// dialect.
|
|
|
|
void printResourceHandle(const AsmDialectResourceHandle &resource);
|
|
|
|
|
|
|
|
void printAffineMap(AffineMap map);
|
|
|
|
void
|
|
|
|
printAffineExpr(AffineExpr expr,
|
|
|
|
function_ref<void(unsigned, bool)> printValueName = nullptr);
|
|
|
|
void printAffineConstraint(AffineExpr expr, bool isEq);
|
|
|
|
void printIntegerSet(IntegerSet set);
|
|
|
|
|
2023-09-04 18:19:18 +02:00
|
|
|
LogicalResult pushCyclicPrinting(const void *opaquePointer);
|
|
|
|
|
|
|
|
void popCyclicPrinting();
|
|
|
|
|
2023-12-08 11:34:44 -08:00
|
|
|
void printDimensionList(ArrayRef<int64_t> shape);
|
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
protected:
|
|
|
|
void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs = {},
|
|
|
|
bool withKeyword = false);
|
|
|
|
void printNamedAttribute(NamedAttribute attr);
|
|
|
|
void printTrailingLocation(Location loc, bool allowAlias = true);
|
2022-11-28 18:35:00 -08:00
|
|
|
void printLocationInternal(LocationAttr loc, bool pretty = false,
|
|
|
|
bool isTopLevel = false);
|
2022-10-22 14:01:41 -07:00
|
|
|
|
|
|
|
/// Print a dense elements attribute. If 'allowHex' is true, a hex string is
|
|
|
|
/// used instead of individual elements when the elements attr is large.
|
|
|
|
void printDenseElementsAttr(DenseElementsAttr attr, bool allowHex);
|
|
|
|
|
|
|
|
/// Print a dense string elements attribute.
|
|
|
|
void printDenseStringElementsAttr(DenseStringElementsAttr attr);
|
|
|
|
|
|
|
|
/// Print a dense elements attribute. If 'allowHex' is true, a hex string is
|
|
|
|
/// used instead of individual elements when the elements attr is large.
|
|
|
|
void printDenseIntOrFPElementsAttr(DenseIntOrFPElementsAttr attr,
|
|
|
|
bool allowHex);
|
|
|
|
|
|
|
|
/// Print a dense array attribute.
|
|
|
|
void printDenseArrayAttr(DenseArrayAttr attr);
|
|
|
|
|
|
|
|
void printDialectAttribute(Attribute attr);
|
|
|
|
void printDialectType(Type type);
|
|
|
|
|
|
|
|
/// Print an escaped string, wrapped with "".
|
|
|
|
void printEscapedString(StringRef str);
|
|
|
|
|
|
|
|
/// Print a hex string, wrapped with "".
|
|
|
|
void printHexString(StringRef str);
|
|
|
|
void printHexString(ArrayRef<char> data);
|
|
|
|
|
|
|
|
/// This enum is used to represent the binding strength of the enclosing
|
|
|
|
/// context that an AffineExprStorage is being printed in, so we can
|
|
|
|
/// intelligently produce parens.
|
|
|
|
enum class BindingStrength {
|
|
|
|
Weak, // + and -
|
|
|
|
Strong, // All other binary operators.
|
|
|
|
};
|
|
|
|
void printAffineExprInternal(
|
|
|
|
AffineExpr expr, BindingStrength enclosingTightness,
|
|
|
|
function_ref<void(unsigned, bool)> printValueName = nullptr);
|
|
|
|
|
|
|
|
/// The output stream for the printer.
|
|
|
|
raw_ostream &os;
|
|
|
|
|
|
|
|
/// An underlying assembly printer state.
|
|
|
|
AsmStateImpl &state;
|
|
|
|
|
|
|
|
/// A set of flags to control the printer's behavior.
|
|
|
|
OpPrintingFlags printerFlags;
|
|
|
|
|
|
|
|
/// A tracker for the number of new lines emitted during printing.
|
|
|
|
NewLineCounter newLine;
|
|
|
|
};
|
|
|
|
} // namespace mlir
|
|
|
|
|
2019-10-07 13:54:16 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2020-11-09 21:50:31 -08:00
|
|
|
// AliasInitializer
|
2019-10-07 13:54:16 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-02-04 13:01:06 -08:00
|
|
|
|
2018-07-17 16:56:54 -07:00
|
|
|
namespace {
|
2020-11-12 23:33:43 -08:00
|
|
|
/// This class represents a specific instance of a symbol Alias.
|
|
|
|
class SymbolAlias {
|
|
|
|
public:
|
2022-11-16 16:26:18 -08:00
|
|
|
SymbolAlias(StringRef name, uint32_t suffixIndex, bool isType,
|
|
|
|
bool isDeferrable)
|
|
|
|
: name(name), suffixIndex(suffixIndex), isType(isType),
|
|
|
|
isDeferrable(isDeferrable) {}
|
2020-11-12 23:33:43 -08:00
|
|
|
|
|
|
|
/// Print this alias to the given stream.
|
|
|
|
void print(raw_ostream &os) const {
|
2022-11-16 16:26:18 -08:00
|
|
|
os << (isType ? "!" : "#") << name;
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
if (suffixIndex) {
|
|
|
|
if (isdigit(name.back()))
|
|
|
|
os << '_';
|
2020-11-12 23:33:43 -08:00
|
|
|
os << suffixIndex;
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
}
|
2020-11-12 23:33:43 -08:00
|
|
|
}
|
|
|
|
|
2022-11-16 16:26:18 -08:00
|
|
|
/// Returns true if this is a type alias.
|
|
|
|
bool isTypeAlias() const { return isType; }
|
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
/// Returns true if this alias supports deferred resolution when parsing.
|
|
|
|
bool canBeDeferred() const { return isDeferrable; }
|
|
|
|
|
|
|
|
private:
|
|
|
|
/// The main name of the alias.
|
|
|
|
StringRef name;
|
2022-10-22 14:01:41 -07:00
|
|
|
/// The suffix index of the alias.
|
2022-11-16 16:26:18 -08:00
|
|
|
uint32_t suffixIndex : 30;
|
|
|
|
/// A flag indicating whether this alias is for a type.
|
|
|
|
bool isType : 1;
|
2020-11-12 23:33:43 -08:00
|
|
|
/// A flag indicating whether this alias may be deferred or not.
|
|
|
|
bool isDeferrable : 1;
|
2024-09-28 18:15:14 -07:00
|
|
|
|
|
|
|
public:
|
|
|
|
/// Used to avoid printing incomplete aliases for recursive types.
|
|
|
|
bool isPrinted = false;
|
2020-11-12 23:33:43 -08:00
|
|
|
};
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// This class represents a utility that initializes the set of attribute and
|
|
|
|
/// type aliases, without the need to store the extra information within the
|
|
|
|
/// main AliasState class or pass it around via function arguments.
|
|
|
|
class AliasInitializer {
|
2018-07-18 10:16:05 -07:00
|
|
|
public:
|
2020-11-09 21:50:31 -08:00
|
|
|
AliasInitializer(
|
|
|
|
DialectInterfaceCollection<OpAsmDialectInterface> &interfaces,
|
|
|
|
llvm::BumpPtrAllocator &aliasAllocator)
|
|
|
|
: interfaces(interfaces), aliasAllocator(aliasAllocator),
|
|
|
|
aliasOS(aliasBuffer) {}
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
void initialize(Operation *op, const OpPrintingFlags &printerFlags,
|
2022-11-16 16:26:18 -08:00
|
|
|
llvm::MapVector<const void *, SymbolAlias> &attrTypeToAlias);
|
2019-01-10 22:08:39 -08:00
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
/// Visit the given attribute to see if it has an alias. `canBeDeferred` is
|
|
|
|
/// set to true if the originator of this attribute can resolve the alias
|
|
|
|
/// after parsing has completed (e.g. in the case of operation locations).
|
2022-11-28 18:35:00 -08:00
|
|
|
/// `elideType` indicates if the type of the attribute should be skipped when
|
|
|
|
/// looking for nested aliases. Returns the maximum alias depth of the
|
|
|
|
/// attribute, and the alias index of this attribute.
|
|
|
|
std::pair<size_t, size_t> visit(Attribute attr, bool canBeDeferred = false,
|
|
|
|
bool elideType = false) {
|
|
|
|
return visitImpl(attr, aliases, canBeDeferred, elideType);
|
2022-10-22 14:01:41 -07:00
|
|
|
}
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
/// Visit the given type to see if it has an alias. `canBeDeferred` is
|
|
|
|
/// set to true if the originator of this attribute can resolve the alias
|
|
|
|
/// after parsing has completed. Returns the maximum alias depth of the type,
|
|
|
|
/// and the alias index of this type.
|
|
|
|
std::pair<size_t, size_t> visit(Type type, bool canBeDeferred = false) {
|
|
|
|
return visitImpl(type, aliases, canBeDeferred);
|
|
|
|
}
|
2019-08-21 16:50:30 -07:00
|
|
|
|
2019-05-06 10:36:32 -07:00
|
|
|
private:
|
2022-10-22 14:01:41 -07:00
|
|
|
struct InProgressAliasInfo {
|
2022-11-16 16:26:18 -08:00
|
|
|
InProgressAliasInfo()
|
|
|
|
: aliasDepth(0), isType(false), canBeDeferred(false) {}
|
2024-09-17 14:27:31 -07:00
|
|
|
InProgressAliasInfo(StringRef alias)
|
|
|
|
: alias(alias), aliasDepth(1), isType(false), canBeDeferred(false) {}
|
2022-10-22 14:01:41 -07:00
|
|
|
|
|
|
|
bool operator<(const InProgressAliasInfo &rhs) const {
|
2022-11-16 16:26:18 -08:00
|
|
|
// Order first by depth, then by attr/type kind, and then by name.
|
2022-10-22 14:01:41 -07:00
|
|
|
if (aliasDepth != rhs.aliasDepth)
|
|
|
|
return aliasDepth < rhs.aliasDepth;
|
2022-11-16 16:26:18 -08:00
|
|
|
if (isType != rhs.isType)
|
|
|
|
return isType;
|
2022-10-22 14:01:41 -07:00
|
|
|
return alias < rhs.alias;
|
|
|
|
}
|
|
|
|
|
2022-12-04 19:58:32 -08:00
|
|
|
/// The alias for the attribute or type, or std::nullopt if the value has no
|
|
|
|
/// alias.
|
2023-01-14 01:25:58 -08:00
|
|
|
std::optional<StringRef> alias;
|
2022-10-22 14:01:41 -07:00
|
|
|
/// The alias depth of this attribute or type, i.e. an indication of the
|
|
|
|
/// relative ordering of when to print this alias.
|
2022-11-16 16:26:18 -08:00
|
|
|
unsigned aliasDepth : 30;
|
|
|
|
/// If this alias represents a type or an attribute.
|
|
|
|
bool isType : 1;
|
2022-10-22 14:01:41 -07:00
|
|
|
/// If this alias can be deferred or not.
|
|
|
|
bool canBeDeferred : 1;
|
2022-11-28 18:35:00 -08:00
|
|
|
/// Indices for child aliases.
|
|
|
|
SmallVector<size_t> childIndices;
|
2022-10-22 14:01:41 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
/// Visit the given attribute or type to see if it has an alias.
|
|
|
|
/// `canBeDeferred` is set to true if the originator of this value can resolve
|
|
|
|
/// the alias after parsing has completed (e.g. in the case of operation
|
2022-11-28 18:35:00 -08:00
|
|
|
/// locations). Returns the maximum alias depth of the value, and its alias
|
|
|
|
/// index.
|
|
|
|
template <typename T, typename... PrintArgs>
|
|
|
|
std::pair<size_t, size_t>
|
|
|
|
visitImpl(T value,
|
|
|
|
llvm::MapVector<const void *, InProgressAliasInfo> &aliases,
|
|
|
|
bool canBeDeferred, PrintArgs &&...printArgs);
|
|
|
|
|
|
|
|
/// Mark the given alias as non-deferrable.
|
|
|
|
void markAliasNonDeferrable(size_t aliasIndex);
|
2022-10-22 14:01:41 -07:00
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// Try to generate an alias for the provided symbol. If an alias is
|
|
|
|
/// generated, the provided alias mapping and reverse mapping are updated.
|
|
|
|
template <typename T>
|
2022-11-16 16:26:18 -08:00
|
|
|
void generateAlias(T symbol, InProgressAliasInfo &alias, bool canBeDeferred);
|
2022-10-22 14:01:41 -07:00
|
|
|
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
/// Uniques the given alias name within the printer by generating name index
|
|
|
|
/// used as alias name suffix.
|
|
|
|
static unsigned
|
|
|
|
uniqueAliasNameIndex(StringRef alias, llvm::StringMap<unsigned> &nameCounts,
|
|
|
|
llvm::StringSet<llvm::BumpPtrAllocator &> &usedAliases);
|
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
/// Given a collection of aliases and symbols, initialize a mapping from a
|
|
|
|
/// symbol to a given alias.
|
2022-11-16 16:26:18 -08:00
|
|
|
static void initializeAliases(
|
|
|
|
llvm::MapVector<const void *, InProgressAliasInfo> &visitedSymbols,
|
|
|
|
llvm::MapVector<const void *, SymbolAlias> &symbolToAlias);
|
2018-08-07 14:24:38 -07:00
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// The set of asm interfaces within the context.
|
|
|
|
DialectInterfaceCollection<OpAsmDialectInterface> &interfaces;
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
/// An allocator used for alias names.
|
2020-11-09 21:50:31 -08:00
|
|
|
llvm::BumpPtrAllocator &aliasAllocator;
|
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
/// The set of built aliases.
|
2022-11-16 16:26:18 -08:00
|
|
|
llvm::MapVector<const void *, InProgressAliasInfo> aliases;
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
/// Storage and stream used when generating an alias.
|
|
|
|
SmallString<32> aliasBuffer;
|
|
|
|
llvm::raw_svector_ostream aliasOS;
|
|
|
|
};
|
|
|
|
|
|
|
|
/// This class implements a dummy OpAsmPrinter that doesn't print any output,
|
|
|
|
/// and merely collects the attributes and types that *would* be printed in a
|
|
|
|
/// normal print invocation so that we can generate proper aliases. This allows
|
|
|
|
/// for us to generate aliases only for the attributes and types that would be
|
|
|
|
/// in the output, and trims down unnecessary output.
|
|
|
|
class DummyAliasOperationPrinter : private OpAsmPrinter {
|
|
|
|
public:
|
2021-07-10 16:39:44 +00:00
|
|
|
explicit DummyAliasOperationPrinter(const OpPrintingFlags &printerFlags,
|
2020-11-09 21:50:31 -08:00
|
|
|
AliasInitializer &initializer)
|
2021-07-10 16:39:44 +00:00
|
|
|
: printerFlags(printerFlags), initializer(initializer) {}
|
2020-11-09 21:50:31 -08:00
|
|
|
|
2022-10-05 18:31:22 +00:00
|
|
|
/// Prints the entire operation with the custom assembly form, if available,
|
|
|
|
/// or the generic assembly form, otherwise.
|
|
|
|
void printCustomOrGenericOp(Operation *op) override {
|
2020-11-09 21:50:47 -08:00
|
|
|
// Visit the operation location.
|
|
|
|
if (printerFlags.shouldPrintDebugInfo())
|
2020-11-12 23:33:43 -08:00
|
|
|
initializer.visit(op->getLoc(), /*canBeDeferred=*/true);
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
// If requested, always print the generic form.
|
|
|
|
if (!printerFlags.shouldPrintGenericOpForm()) {
|
2023-01-16 23:26:28 +00:00
|
|
|
op->getName().printAssembly(op, *this, /*defaultDialect=*/"");
|
|
|
|
return;
|
2020-11-09 21:50:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise print with the generic assembly form.
|
|
|
|
printGenericOp(op);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
/// Print the given operation in the generic form.
|
2021-08-28 03:03:15 +00:00
|
|
|
void printGenericOp(Operation *op, bool printOpName = true) override {
|
2021-01-08 02:09:48 +09:00
|
|
|
// Consider nested operations for aliases.
|
2023-03-13 14:33:31 +01:00
|
|
|
if (!printerFlags.shouldSkipRegions()) {
|
|
|
|
for (Region ®ion : op->getRegions())
|
|
|
|
printRegion(region, /*printEntryBlockArgs=*/true,
|
|
|
|
/*printBlockTerminators=*/true);
|
|
|
|
}
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
// Visit all the types used in the operation.
|
|
|
|
for (Type type : op->getOperandTypes())
|
|
|
|
printType(type);
|
|
|
|
for (Type type : op->getResultTypes())
|
|
|
|
printType(type);
|
|
|
|
|
|
|
|
// Consider the attributes of the operation for aliases.
|
|
|
|
for (const NamedAttribute &attr : op->getAttrs())
|
2021-11-18 05:23:32 +00:00
|
|
|
printAttribute(attr.getValue());
|
2020-11-09 21:50:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Print the given block. If 'printBlockArgs' is false, the arguments of the
|
|
|
|
/// block are not printed. If 'printBlockTerminator' is false, the terminator
|
|
|
|
/// operation of the block is not printed.
|
|
|
|
void print(Block *block, bool printBlockArgs = true,
|
|
|
|
bool printBlockTerminator = true) {
|
|
|
|
// Consider the types of the block arguments for aliases if 'printBlockArgs'
|
|
|
|
// is set to true.
|
|
|
|
if (printBlockArgs) {
|
2021-05-23 14:08:31 -07:00
|
|
|
for (BlockArgument arg : block->getArguments()) {
|
|
|
|
printType(arg.getType());
|
|
|
|
|
|
|
|
// Visit the argument location.
|
|
|
|
if (printerFlags.shouldPrintDebugInfo())
|
|
|
|
// TODO: Allow deferring argument locations.
|
|
|
|
initializer.visit(arg.getLoc(), /*canBeDeferred=*/false);
|
|
|
|
}
|
2020-11-09 21:50:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Consider the operations within this block, ignoring the terminator if
|
|
|
|
// requested.
|
2021-05-28 07:21:41 -04:00
|
|
|
bool hasTerminator =
|
|
|
|
!block->empty() && block->back().hasTrait<OpTrait::IsTerminator>();
|
2020-11-09 21:50:31 -08:00
|
|
|
auto range = llvm::make_range(
|
2021-05-28 07:21:41 -04:00
|
|
|
block->begin(),
|
|
|
|
std::prev(block->end(),
|
|
|
|
(!hasTerminator || printBlockTerminator) ? 0 : 1));
|
2020-11-09 21:50:31 -08:00
|
|
|
for (Operation &op : range)
|
2022-10-05 18:31:22 +00:00
|
|
|
printCustomOrGenericOp(&op);
|
2020-11-09 21:50:31 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Print the given region.
|
|
|
|
void printRegion(Region ®ion, bool printEntryBlockArgs,
|
2021-03-11 23:58:02 +00:00
|
|
|
bool printBlockTerminators,
|
|
|
|
bool printEmptyBlock = false) override {
|
2020-11-09 21:50:31 -08:00
|
|
|
if (region.empty())
|
|
|
|
return;
|
2023-03-13 14:33:31 +01:00
|
|
|
if (printerFlags.shouldSkipRegions()) {
|
|
|
|
os << "{...}";
|
|
|
|
return;
|
|
|
|
}
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
auto *entryBlock = ®ion.front();
|
|
|
|
print(entryBlock, printEntryBlockArgs, printBlockTerminators);
|
|
|
|
for (Block &b : llvm::drop_begin(region, 1))
|
|
|
|
print(&b);
|
|
|
|
}
|
|
|
|
|
2021-05-23 14:08:31 -07:00
|
|
|
void printRegionArgument(BlockArgument arg, ArrayRef<NamedAttribute> argAttrs,
|
|
|
|
bool omitType) override {
|
|
|
|
printType(arg.getType());
|
|
|
|
// Visit the argument location.
|
|
|
|
if (printerFlags.shouldPrintDebugInfo())
|
|
|
|
// TODO: Allow deferring argument locations.
|
|
|
|
initializer.visit(arg.getLoc(), /*canBeDeferred=*/false);
|
|
|
|
}
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// Consider the given type to be printed for an alias.
|
|
|
|
void printType(Type type) override { initializer.visit(type); }
|
|
|
|
|
|
|
|
/// Consider the given attribute to be printed for an alias.
|
|
|
|
void printAttribute(Attribute attr) override { initializer.visit(attr); }
|
|
|
|
void printAttributeWithoutType(Attribute attr) override {
|
|
|
|
printAttribute(attr);
|
|
|
|
}
|
2021-12-08 01:24:51 +00:00
|
|
|
LogicalResult printAlias(Attribute attr) override {
|
|
|
|
initializer.visit(attr);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
LogicalResult printAlias(Type type) override {
|
|
|
|
initializer.visit(type);
|
|
|
|
return success();
|
|
|
|
}
|
2020-11-09 21:50:31 -08:00
|
|
|
|
2022-09-29 14:43:08 -07:00
|
|
|
/// Consider the given location to be printed for an alias.
|
|
|
|
void printOptionalLocationSpecifier(Location loc) override {
|
|
|
|
printAttribute(loc);
|
|
|
|
}
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// Print the given set of attributes with names not included within
|
|
|
|
/// 'elidedAttrs'.
|
|
|
|
void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs = {}) override {
|
2021-03-05 12:42:24 -08:00
|
|
|
if (attrs.empty())
|
|
|
|
return;
|
|
|
|
if (elidedAttrs.empty()) {
|
|
|
|
for (const NamedAttribute &attr : attrs)
|
2021-11-18 05:23:32 +00:00
|
|
|
printAttribute(attr.getValue());
|
2021-03-05 12:42:24 -08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
llvm::SmallDenseSet<StringRef> elidedAttrsSet(elidedAttrs.begin(),
|
|
|
|
elidedAttrs.end());
|
|
|
|
for (const NamedAttribute &attr : attrs)
|
2021-11-18 05:23:32 +00:00
|
|
|
if (!elidedAttrsSet.contains(attr.getName().strref()))
|
|
|
|
printAttribute(attr.getValue());
|
2020-11-09 21:50:31 -08:00
|
|
|
}
|
|
|
|
void printOptionalAttrDictWithKeyword(
|
|
|
|
ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs = {}) override {
|
|
|
|
printOptionalAttrDict(attrs, elidedAttrs);
|
|
|
|
}
|
|
|
|
|
2021-04-15 12:14:16 -07:00
|
|
|
/// Return a null stream as the output stream, this will ignore any data fed
|
|
|
|
/// to it.
|
|
|
|
raw_ostream &getStream() const override { return os; }
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
/// The following are hooks of `OpAsmPrinter` that are not necessary for
|
|
|
|
/// determining potential aliases.
|
2022-11-28 18:35:00 -08:00
|
|
|
void printFloat(const APFloat &) override {}
|
2020-11-09 21:50:31 -08:00
|
|
|
void printAffineMapOfSSAIds(AffineMapAttr, ValueRange) override {}
|
2021-04-29 13:15:21 +02:00
|
|
|
void printAffineExprOfSSAIds(AffineExpr, ValueRange, ValueRange) override {}
|
2020-12-14 11:53:34 -08:00
|
|
|
void printNewline() override {}
|
2022-10-27 09:39:52 +02:00
|
|
|
void increaseIndent() override {}
|
|
|
|
void decreaseIndent() override {}
|
2020-11-09 21:50:31 -08:00
|
|
|
void printOperand(Value) override {}
|
|
|
|
void printOperand(Value, raw_ostream &os) override {
|
|
|
|
// Users expect the output string to have at least the prefixed % to signal
|
|
|
|
// a value name. To maintain this invariant, emit a name even if it is
|
|
|
|
// guaranteed to go unused.
|
|
|
|
os << "%";
|
|
|
|
}
|
2021-10-12 13:29:29 -07:00
|
|
|
void printKeywordOrString(StringRef) override {}
|
2023-09-09 00:06:38 +02:00
|
|
|
void printString(StringRef) override {}
|
2022-11-28 18:35:00 -08:00
|
|
|
void printResourceHandle(const AsmDialectResourceHandle &) override {}
|
2020-11-09 21:50:31 -08:00
|
|
|
void printSymbolName(StringRef) override {}
|
|
|
|
void printSuccessor(Block *) override {}
|
|
|
|
void printSuccessorAndUseList(Block *, ValueRange) override {}
|
|
|
|
void shadowRegionArgs(Region &, ValueRange) override {}
|
|
|
|
|
|
|
|
/// The printer flags to use when determining potential aliases.
|
|
|
|
const OpPrintingFlags &printerFlags;
|
|
|
|
|
|
|
|
/// The initializer to use when identifying aliases.
|
|
|
|
AliasInitializer &initializer;
|
2021-04-15 12:14:16 -07:00
|
|
|
|
|
|
|
/// A dummy output stream.
|
|
|
|
mutable llvm::raw_null_ostream os;
|
2018-07-17 16:56:54 -07:00
|
|
|
};
|
2022-11-28 18:35:00 -08:00
|
|
|
|
|
|
|
class DummyAliasDialectAsmPrinter : public DialectAsmPrinter {
|
|
|
|
public:
|
|
|
|
explicit DummyAliasDialectAsmPrinter(AliasInitializer &initializer,
|
|
|
|
bool canBeDeferred,
|
|
|
|
SmallVectorImpl<size_t> &childIndices)
|
|
|
|
: initializer(initializer), canBeDeferred(canBeDeferred),
|
|
|
|
childIndices(childIndices) {}
|
|
|
|
|
|
|
|
/// Print the given attribute/type, visiting any nested aliases that would be
|
|
|
|
/// generated as part of printing. Returns the maximum alias depth found while
|
|
|
|
/// printing the given value.
|
|
|
|
template <typename T, typename... PrintArgs>
|
|
|
|
size_t printAndVisitNestedAliases(T value, PrintArgs &&...printArgs) {
|
|
|
|
printAndVisitNestedAliasesImpl(value, printArgs...);
|
|
|
|
return maxAliasDepth;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
/// Print the given attribute/type, visiting any nested aliases that would be
|
|
|
|
/// generated as part of printing.
|
|
|
|
void printAndVisitNestedAliasesImpl(Attribute attr, bool elideType) {
|
2022-12-05 11:12:54 -08:00
|
|
|
if (!isa<BuiltinDialect>(attr.getDialect())) {
|
|
|
|
attr.getDialect().printAttribute(attr, *this);
|
2022-11-28 18:35:00 -08:00
|
|
|
|
2022-12-05 11:12:54 -08:00
|
|
|
// Process the builtin attributes.
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (llvm::isa<AffineMapAttr, DenseArrayAttr, FloatAttr, IntegerAttr,
|
|
|
|
IntegerSetAttr, UnitAttr>(attr)) {
|
2022-11-28 18:35:00 -08:00
|
|
|
return;
|
2023-07-11 07:30:18 +00:00
|
|
|
} else if (auto distinctAttr = dyn_cast<DistinctAttr>(attr)) {
|
|
|
|
printAttribute(distinctAttr.getReferencedAttr());
|
2022-12-05 11:12:54 -08:00
|
|
|
} else if (auto dictAttr = dyn_cast<DictionaryAttr>(attr)) {
|
2022-11-28 18:35:00 -08:00
|
|
|
for (const NamedAttribute &nestedAttr : dictAttr.getValue()) {
|
|
|
|
printAttribute(nestedAttr.getName());
|
|
|
|
printAttribute(nestedAttr.getValue());
|
|
|
|
}
|
|
|
|
} else if (auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
|
|
|
|
for (Attribute nestedAttr : arrayAttr.getValue())
|
|
|
|
printAttribute(nestedAttr);
|
|
|
|
} else if (auto typeAttr = dyn_cast<TypeAttr>(attr)) {
|
|
|
|
printType(typeAttr.getValue());
|
|
|
|
} else if (auto locAttr = dyn_cast<OpaqueLoc>(attr)) {
|
|
|
|
printAttribute(locAttr.getFallbackLocation());
|
|
|
|
} else if (auto locAttr = dyn_cast<NameLoc>(attr)) {
|
|
|
|
if (!isa<UnknownLoc>(locAttr.getChildLoc()))
|
|
|
|
printAttribute(locAttr.getChildLoc());
|
|
|
|
} else if (auto locAttr = dyn_cast<CallSiteLoc>(attr)) {
|
|
|
|
printAttribute(locAttr.getCallee());
|
|
|
|
printAttribute(locAttr.getCaller());
|
|
|
|
} else if (auto locAttr = dyn_cast<FusedLoc>(attr)) {
|
|
|
|
if (Attribute metadata = locAttr.getMetadata())
|
|
|
|
printAttribute(metadata);
|
|
|
|
for (Location nestedLoc : locAttr.getLocations())
|
|
|
|
printAttribute(nestedLoc);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Don't print the type if we must elide it, or if it is a None type.
|
|
|
|
if (!elideType) {
|
2023-05-11 11:10:46 +02:00
|
|
|
if (auto typedAttr = llvm::dyn_cast<TypedAttr>(attr)) {
|
2022-11-28 18:35:00 -08:00
|
|
|
Type attrType = typedAttr.getType();
|
2023-05-11 11:10:46 +02:00
|
|
|
if (!llvm::isa<NoneType>(attrType))
|
2022-11-28 18:35:00 -08:00
|
|
|
printType(attrType);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
void printAndVisitNestedAliasesImpl(Type type) {
|
|
|
|
if (!isa<BuiltinDialect>(type.getDialect()))
|
|
|
|
return type.getDialect().printType(type, *this);
|
|
|
|
|
|
|
|
// Only visit the layout of memref if it isn't the identity.
|
2023-05-11 11:10:46 +02:00
|
|
|
if (auto memrefTy = llvm::dyn_cast<MemRefType>(type)) {
|
2022-11-28 18:35:00 -08:00
|
|
|
printType(memrefTy.getElementType());
|
|
|
|
MemRefLayoutAttrInterface layout = memrefTy.getLayout();
|
2023-05-11 11:10:46 +02:00
|
|
|
if (!llvm::isa<AffineMapAttr>(layout) || !layout.isIdentity())
|
2022-11-28 18:35:00 -08:00
|
|
|
printAttribute(memrefTy.getLayout());
|
|
|
|
if (memrefTy.getMemorySpace())
|
|
|
|
printAttribute(memrefTy.getMemorySpace());
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// For most builtin types, we can simply walk the sub elements.
|
2023-01-20 21:39:13 -08:00
|
|
|
auto visitFn = [&](auto element) {
|
|
|
|
if (element)
|
|
|
|
(void)printAlias(element);
|
|
|
|
};
|
|
|
|
type.walkImmediateSubElements(visitFn, visitFn);
|
2022-11-28 18:35:00 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Consider the given type to be printed for an alias.
|
|
|
|
void printType(Type type) override {
|
|
|
|
recordAliasResult(initializer.visit(type, canBeDeferred));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Consider the given attribute to be printed for an alias.
|
|
|
|
void printAttribute(Attribute attr) override {
|
|
|
|
recordAliasResult(initializer.visit(attr, canBeDeferred));
|
|
|
|
}
|
|
|
|
void printAttributeWithoutType(Attribute attr) override {
|
|
|
|
recordAliasResult(
|
|
|
|
initializer.visit(attr, canBeDeferred, /*elideType=*/true));
|
|
|
|
}
|
|
|
|
LogicalResult printAlias(Attribute attr) override {
|
|
|
|
printAttribute(attr);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
LogicalResult printAlias(Type type) override {
|
|
|
|
printType(type);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Record the alias result of a child element.
|
|
|
|
void recordAliasResult(std::pair<size_t, size_t> aliasDepthAndIndex) {
|
|
|
|
childIndices.push_back(aliasDepthAndIndex.second);
|
|
|
|
if (aliasDepthAndIndex.first > maxAliasDepth)
|
|
|
|
maxAliasDepth = aliasDepthAndIndex.first;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return a null stream as the output stream, this will ignore any data fed
|
|
|
|
/// to it.
|
|
|
|
raw_ostream &getStream() const override { return os; }
|
|
|
|
|
|
|
|
/// The following are hooks of `DialectAsmPrinter` that are not necessary for
|
|
|
|
/// determining potential aliases.
|
|
|
|
void printFloat(const APFloat &) override {}
|
|
|
|
void printKeywordOrString(StringRef) override {}
|
2023-09-09 00:06:38 +02:00
|
|
|
void printString(StringRef) override {}
|
2022-11-28 18:35:00 -08:00
|
|
|
void printSymbolName(StringRef) override {}
|
|
|
|
void printResourceHandle(const AsmDialectResourceHandle &) override {}
|
|
|
|
|
2023-09-04 18:19:18 +02:00
|
|
|
LogicalResult pushCyclicPrinting(const void *opaquePointer) override {
|
|
|
|
return success(cyclicPrintingStack.insert(opaquePointer));
|
|
|
|
}
|
|
|
|
|
|
|
|
void popCyclicPrinting() override { cyclicPrintingStack.pop_back(); }
|
|
|
|
|
|
|
|
/// Stack of potentially cyclic mutable attributes or type currently being
|
|
|
|
/// printed.
|
|
|
|
SetVector<const void *> cyclicPrintingStack;
|
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
/// The initializer to use when identifying aliases.
|
|
|
|
AliasInitializer &initializer;
|
|
|
|
|
|
|
|
/// If the aliases visited by this printer can be deferred.
|
|
|
|
bool canBeDeferred;
|
|
|
|
|
|
|
|
/// The indices of child aliases.
|
|
|
|
SmallVectorImpl<size_t> &childIndices;
|
|
|
|
|
|
|
|
/// The maximum alias depth found by the printer.
|
|
|
|
size_t maxAliasDepth = 0;
|
|
|
|
|
|
|
|
/// A dummy output stream.
|
|
|
|
mutable llvm::raw_null_ostream os;
|
|
|
|
};
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace
|
2018-07-17 16:56:54 -07:00
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
/// Sanitize the given name such that it can be used as a valid identifier. If
|
|
|
|
/// the string needs to be modified in any way, the provided buffer is used to
|
|
|
|
/// store the new copy,
|
|
|
|
static StringRef sanitizeIdentifier(StringRef name, SmallString<16> &buffer,
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
StringRef allowedPunctChars = "$._-") {
|
2020-10-30 00:30:59 -07:00
|
|
|
assert(!name.empty() && "Shouldn't have an empty name here");
|
2019-01-10 22:08:39 -08:00
|
|
|
|
2024-06-10 19:12:34 -05:00
|
|
|
auto validChar = [&](char ch) {
|
|
|
|
return llvm::isAlnum(ch) || allowedPunctChars.contains(ch);
|
|
|
|
};
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
auto copyNameToBuffer = [&] {
|
|
|
|
for (char ch : name) {
|
2024-06-10 19:12:34 -05:00
|
|
|
if (validChar(ch))
|
2020-10-30 00:30:59 -07:00
|
|
|
buffer.push_back(ch);
|
|
|
|
else if (ch == ' ')
|
|
|
|
buffer.push_back('_');
|
|
|
|
else
|
|
|
|
buffer.append(llvm::utohexstr((unsigned char)ch));
|
|
|
|
}
|
|
|
|
};
|
2019-01-10 22:08:39 -08:00
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// Check to see if this name is valid. If it starts with a digit, then it
|
|
|
|
// could conflict with the autogenerated numeric ID's, so add an underscore
|
|
|
|
// prefix to avoid problems.
|
2024-06-10 19:12:34 -05:00
|
|
|
if (isdigit(name[0]) || (!validChar(name[0]) && name[0] != ' ')) {
|
2020-10-30 00:30:59 -07:00
|
|
|
buffer.push_back('_');
|
|
|
|
copyNameToBuffer();
|
|
|
|
return buffer;
|
2019-01-10 22:08:39 -08:00
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// Check to see that the name consists of only valid identifier characters.
|
|
|
|
for (char ch : name) {
|
2024-06-10 19:12:34 -05:00
|
|
|
if (!validChar(ch)) {
|
2020-10-30 00:30:59 -07:00
|
|
|
copyNameToBuffer();
|
|
|
|
return buffer;
|
|
|
|
}
|
2019-01-10 22:08:39 -08:00
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// If there are no invalid characters, return the original name.
|
|
|
|
return name;
|
2018-07-20 09:35:47 -07:00
|
|
|
}
|
|
|
|
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
unsigned AliasInitializer::uniqueAliasNameIndex(
|
|
|
|
StringRef alias, llvm::StringMap<unsigned> &nameCounts,
|
|
|
|
llvm::StringSet<llvm::BumpPtrAllocator &> &usedAliases) {
|
|
|
|
if (!usedAliases.count(alias)) {
|
|
|
|
usedAliases.insert(alias);
|
|
|
|
// 0 is not printed in SymbolAlias.
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
// Otherwise, we had a conflict - probe until we find a unique name.
|
|
|
|
SmallString<64> probeAlias(alias);
|
|
|
|
// alias with trailing digit will be printed as _N
|
|
|
|
if (isdigit(alias.back()))
|
|
|
|
probeAlias.push_back('_');
|
|
|
|
// nameCounts start from 1 because 0 is not printed in SymbolAlias.
|
|
|
|
if (nameCounts[probeAlias] == 0)
|
|
|
|
nameCounts[probeAlias] = 1;
|
|
|
|
// This is guaranteed to terminate (and usually in a single iteration)
|
|
|
|
// because it generates new names by incrementing nameCounts.
|
|
|
|
while (true) {
|
|
|
|
unsigned nameIndex = nameCounts[probeAlias]++;
|
|
|
|
probeAlias += llvm::utostr(nameIndex);
|
|
|
|
if (!usedAliases.count(probeAlias)) {
|
|
|
|
usedAliases.insert(probeAlias);
|
|
|
|
return nameIndex;
|
|
|
|
}
|
|
|
|
// Reset probeAlias to the original alias for the next iteration.
|
|
|
|
probeAlias.resize(alias.size() + isdigit(alias.back()) ? 1 : 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
/// Given a collection of aliases and symbols, initialize a mapping from a
|
|
|
|
/// symbol to a given alias.
|
2022-10-22 14:01:41 -07:00
|
|
|
void AliasInitializer::initializeAliases(
|
2022-11-16 16:26:18 -08:00
|
|
|
llvm::MapVector<const void *, InProgressAliasInfo> &visitedSymbols,
|
|
|
|
llvm::MapVector<const void *, SymbolAlias> &symbolToAlias) {
|
2023-07-24 22:04:03 -07:00
|
|
|
SmallVector<std::pair<const void *, InProgressAliasInfo>, 0>
|
|
|
|
unprocessedAliases = visitedSymbols.takeVector();
|
2022-10-22 14:01:41 -07:00
|
|
|
llvm::stable_sort(unprocessedAliases, [](const auto &lhs, const auto &rhs) {
|
|
|
|
return lhs.second < rhs.second;
|
|
|
|
});
|
|
|
|
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
// This keeps track of all of the non-numeric names that are in flight,
|
|
|
|
// allowing us to check for duplicates.
|
|
|
|
llvm::BumpPtrAllocator usedAliasAllocator;
|
|
|
|
llvm::StringSet<llvm::BumpPtrAllocator &> usedAliases(usedAliasAllocator);
|
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
llvm::StringMap<unsigned> nameCounts;
|
|
|
|
for (auto &[symbol, aliasInfo] : unprocessedAliases) {
|
|
|
|
if (!aliasInfo.alias)
|
2020-10-30 00:30:59 -07:00
|
|
|
continue;
|
2022-10-22 14:01:41 -07:00
|
|
|
StringRef alias = *aliasInfo.alias;
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
unsigned nameIndex = uniqueAliasNameIndex(alias, nameCounts, usedAliases);
|
2022-10-22 14:01:41 -07:00
|
|
|
symbolToAlias.insert(
|
2022-11-16 16:26:18 -08:00
|
|
|
{symbol, SymbolAlias(alias, nameIndex, aliasInfo.isType,
|
|
|
|
aliasInfo.canBeDeferred)});
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
void AliasInitializer::initialize(
|
|
|
|
Operation *op, const OpPrintingFlags &printerFlags,
|
2022-11-16 16:26:18 -08:00
|
|
|
llvm::MapVector<const void *, SymbolAlias> &attrTypeToAlias) {
|
2020-11-09 21:50:31 -08:00
|
|
|
// Use a dummy printer when walking the IR so that we can collect the
|
|
|
|
// attributes/types that will actually be used during printing when
|
|
|
|
// considering aliases.
|
|
|
|
DummyAliasOperationPrinter aliasPrinter(printerFlags, *this);
|
2022-10-05 18:31:22 +00:00
|
|
|
aliasPrinter.printCustomOrGenericOp(op);
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2022-11-16 16:26:18 -08:00
|
|
|
// Initialize the aliases.
|
|
|
|
initializeAliases(aliases, attrTypeToAlias);
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
template <typename T, typename... PrintArgs>
|
|
|
|
std::pair<size_t, size_t> AliasInitializer::visitImpl(
|
2022-11-16 16:26:18 -08:00
|
|
|
T value, llvm::MapVector<const void *, InProgressAliasInfo> &aliases,
|
2022-11-28 18:35:00 -08:00
|
|
|
bool canBeDeferred, PrintArgs &&...printArgs) {
|
2022-11-16 16:26:18 -08:00
|
|
|
auto [it, inserted] =
|
|
|
|
aliases.insert({value.getAsOpaquePointer(), InProgressAliasInfo()});
|
2022-11-28 18:35:00 -08:00
|
|
|
size_t aliasIndex = std::distance(aliases.begin(), it);
|
2022-10-22 14:01:41 -07:00
|
|
|
if (!inserted) {
|
|
|
|
// Make sure that the alias isn't deferred if we don't permit it.
|
2020-11-12 23:33:43 -08:00
|
|
|
if (!canBeDeferred)
|
2022-11-28 18:35:00 -08:00
|
|
|
markAliasNonDeferrable(aliasIndex);
|
|
|
|
return {static_cast<size_t>(it->second.aliasDepth), aliasIndex};
|
2020-11-12 23:33:43 -08:00
|
|
|
}
|
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
// Try to generate an alias for this value.
|
2022-11-16 16:26:18 -08:00
|
|
|
generateAlias(value, it->second, canBeDeferred);
|
2024-09-17 14:27:31 -07:00
|
|
|
it->second.isType = std::is_base_of_v<Type, T>;
|
|
|
|
it->second.canBeDeferred = canBeDeferred;
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
// Print the value, capturing any nested elements that require aliases.
|
|
|
|
SmallVector<size_t> childAliases;
|
|
|
|
DummyAliasDialectAsmPrinter printer(*this, canBeDeferred, childAliases);
|
|
|
|
size_t maxAliasDepth =
|
|
|
|
printer.printAndVisitNestedAliases(value, printArgs...);
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
// Make sure to recompute `it` in case the map was reallocated.
|
|
|
|
it = std::next(aliases.begin(), aliasIndex);
|
2020-11-12 23:33:43 -08:00
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
// If we had sub elements, update to account for the depth.
|
|
|
|
it->second.childIndices = std::move(childAliases);
|
|
|
|
if (maxAliasDepth)
|
|
|
|
it->second.aliasDepth = maxAliasDepth + 1;
|
2022-10-22 14:01:41 -07:00
|
|
|
|
|
|
|
// Propagate the alias depth of the value.
|
2022-11-28 18:35:00 -08:00
|
|
|
return {(size_t)it->second.aliasDepth, aliasIndex};
|
|
|
|
}
|
|
|
|
|
|
|
|
void AliasInitializer::markAliasNonDeferrable(size_t aliasIndex) {
|
2023-10-20 09:31:39 -07:00
|
|
|
auto *it = std::next(aliases.begin(), aliasIndex);
|
2023-08-26 16:10:52 +02:00
|
|
|
|
|
|
|
// If already marked non-deferrable stop the recursion.
|
|
|
|
// All children should already be marked non-deferrable as well.
|
|
|
|
if (!it->second.canBeDeferred)
|
|
|
|
return;
|
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
it->second.canBeDeferred = false;
|
|
|
|
|
|
|
|
// Propagate the non-deferrable flag to any child aliases.
|
|
|
|
for (size_t childIndex : it->second.childIndices)
|
|
|
|
markAliasNonDeferrable(childIndex);
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
template <typename T>
|
2022-11-16 16:26:18 -08:00
|
|
|
void AliasInitializer::generateAlias(T symbol, InProgressAliasInfo &alias,
|
|
|
|
bool canBeDeferred) {
|
2021-08-03 17:23:31 +03:00
|
|
|
SmallString<32> nameBuffer;
|
2025-02-19 02:18:59 +08:00
|
|
|
|
|
|
|
OpAsmDialectInterface::AliasResult symbolInterfaceResult =
|
|
|
|
OpAsmDialectInterface::AliasResult::NoAlias;
|
2025-02-19 02:28:49 +08:00
|
|
|
using InterfaceT = std::conditional_t<std::is_base_of_v<Attribute, T>,
|
|
|
|
OpAsmAttrInterface, OpAsmTypeInterface>;
|
|
|
|
if (auto symbolInterface = dyn_cast<InterfaceT>(symbol)) {
|
|
|
|
symbolInterfaceResult = symbolInterface.getAlias(aliasOS);
|
|
|
|
if (symbolInterfaceResult != OpAsmDialectInterface::AliasResult::NoAlias) {
|
|
|
|
nameBuffer = std::move(aliasBuffer);
|
|
|
|
assert(!nameBuffer.empty() && "expected valid alias name");
|
2025-02-19 02:18:59 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (symbolInterfaceResult != OpAsmDialectInterface::AliasResult::FinalAlias) {
|
|
|
|
for (const auto &interface : interfaces) {
|
|
|
|
OpAsmDialectInterface::AliasResult result =
|
|
|
|
interface.getAlias(symbol, aliasOS);
|
|
|
|
if (result == OpAsmDialectInterface::AliasResult::NoAlias)
|
|
|
|
continue;
|
|
|
|
nameBuffer = std::move(aliasBuffer);
|
|
|
|
assert(!nameBuffer.empty() && "expected valid alias name");
|
|
|
|
if (result == OpAsmDialectInterface::AliasResult::FinalAlias)
|
|
|
|
break;
|
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
2021-08-03 17:23:31 +03:00
|
|
|
|
|
|
|
if (nameBuffer.empty())
|
2022-11-16 16:26:18 -08:00
|
|
|
return;
|
2021-08-03 17:23:31 +03:00
|
|
|
|
|
|
|
SmallString<16> tempBuffer;
|
|
|
|
StringRef name =
|
[mlir] Allow trailing digit for alias in AsmPrinter (#127993)
When generating aliases from `OpAsm{Dialect,Type,Attr}Interface`, the
result would be sanitized and if the alias provided by the interface has
a trailing digit, AsmPrinter would attach an underscore to it to
presumably prevent confliction.
#### Motivation
There are two reasons to motivate the change from the old behavior to
the proposed behavior
1. If the type/attribute can generate unique alias from its content,
then the extra trailing underscore added by AsmPrinter will be strange
```mlir
func.func @add(%ct: !ct_L0_) -> !ct_L0_
%ct_0 = bgv.add %ct, %ct : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_1 = bgv.add %ct_0, %ct_0 : (!ct_L0_, !ct_L0_) -> !ct_L0_
%ct_2 = bgv.add %ct_1, %ct_1 : (!ct_L0_, !ct_L0_) -> !ct_L0_
return %ct_2 : !ct_L0_
}
```
Which aesthetically would be better if we have `(!ct_L0, !ct_L0) ->
!ct_L0`
2. The Value name behavior is that, for the first instance, use no
suffix `_N`, which can be similarly applied to alias name. See the IR
above where the first one is called `%ct` and others are called `%ct_N`.
See `uniqueValueName` for detail.
#### Conflict detection
```mlir
!test.type<a = 3> // suggest !name0
!test.type<a = 4> // suggest !name0
!test.another<b = 3> // suggest !name0_
!test.another<b = 4> // suggest !name0_
```
The conflict detection is based on `nameCounts` in `initializeAliases`,
where
In the original way, the first two will get sanitized to `!name0_` and
`initializeAlias` can assign unique id `0, 1, 2, 3` to them.
In the current way, the `initializeAlias` uses `usedAliases` to track
which name has been used, and use such information to generate a suffix
id that will make the printed alias name unique.
The result for the above example is `!name0, !name0_1, !name0_,
!name0_2` now.
2025-03-07 00:35:00 +08:00
|
|
|
sanitizeIdentifier(nameBuffer, tempBuffer, /*allowedPunctChars=*/"$_-");
|
2021-08-03 17:23:31 +03:00
|
|
|
name = name.copy(aliasAllocator);
|
2024-09-17 14:27:31 -07:00
|
|
|
alias = InProgressAliasInfo(name);
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// AliasState
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
/// This class manages the state for type and attribute aliases.
|
|
|
|
class AliasState {
|
|
|
|
public:
|
|
|
|
// Initialize the internal aliases.
|
|
|
|
void
|
|
|
|
initialize(Operation *op, const OpPrintingFlags &printerFlags,
|
|
|
|
DialectInterfaceCollection<OpAsmDialectInterface> &interfaces);
|
|
|
|
|
|
|
|
/// Get an alias for the given attribute if it has one and print it in `os`.
|
|
|
|
/// Returns success if an alias was printed, failure otherwise.
|
|
|
|
LogicalResult getAlias(Attribute attr, raw_ostream &os) const;
|
|
|
|
|
|
|
|
/// Get an alias for the given type if it has one and print it in `os`.
|
|
|
|
/// Returns success if an alias was printed, failure otherwise.
|
|
|
|
LogicalResult getAlias(Type ty, raw_ostream &os) const;
|
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
/// Print all of the referenced aliases that can not be resolved in a deferred
|
|
|
|
/// manner.
|
2022-10-22 14:01:41 -07:00
|
|
|
void printNonDeferredAliases(AsmPrinter::Impl &p, NewLineCounter &newLine) {
|
|
|
|
printAliases(p, newLine, /*isDeferred=*/false);
|
2020-11-12 23:33:43 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Print all of the referenced aliases that support deferred resolution.
|
2022-10-22 14:01:41 -07:00
|
|
|
void printDeferredAliases(AsmPrinter::Impl &p, NewLineCounter &newLine) {
|
|
|
|
printAliases(p, newLine, /*isDeferred=*/true);
|
2020-11-12 23:33:43 -08:00
|
|
|
}
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
private:
|
2020-11-12 23:33:43 -08:00
|
|
|
/// Print all of the referenced aliases that support the provided resolution
|
|
|
|
/// behavior.
|
2022-10-22 14:01:41 -07:00
|
|
|
void printAliases(AsmPrinter::Impl &p, NewLineCounter &newLine,
|
|
|
|
bool isDeferred);
|
2020-11-12 23:33:43 -08:00
|
|
|
|
2022-11-16 16:26:18 -08:00
|
|
|
/// Mapping between attribute/type and alias.
|
|
|
|
llvm::MapVector<const void *, SymbolAlias> attrTypeToAlias;
|
2020-11-09 21:50:31 -08:00
|
|
|
|
|
|
|
/// An allocator used for alias names.
|
|
|
|
llvm::BumpPtrAllocator aliasAllocator;
|
|
|
|
};
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace
|
2020-11-09 21:50:31 -08:00
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
void AliasState::initialize(
|
2020-11-09 21:50:31 -08:00
|
|
|
Operation *op, const OpPrintingFlags &printerFlags,
|
2020-10-30 00:30:59 -07:00
|
|
|
DialectInterfaceCollection<OpAsmDialectInterface> &interfaces) {
|
|
|
|
AliasInitializer initializer(interfaces, aliasAllocator);
|
2022-11-16 16:26:18 -08:00
|
|
|
initializer.initialize(op, printerFlags, attrTypeToAlias);
|
2020-10-30 00:30:59 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult AliasState::getAlias(Attribute attr, raw_ostream &os) const {
|
2023-10-20 09:31:39 -07:00
|
|
|
const auto *it = attrTypeToAlias.find(attr.getAsOpaquePointer());
|
2022-11-16 16:26:18 -08:00
|
|
|
if (it == attrTypeToAlias.end())
|
2020-10-30 00:30:59 -07:00
|
|
|
return failure();
|
2022-11-16 16:26:18 -08:00
|
|
|
it->second.print(os);
|
2020-10-30 00:30:59 -07:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult AliasState::getAlias(Type ty, raw_ostream &os) const {
|
2023-10-20 09:31:39 -07:00
|
|
|
const auto *it = attrTypeToAlias.find(ty.getAsOpaquePointer());
|
2022-11-16 16:26:18 -08:00
|
|
|
if (it == attrTypeToAlias.end())
|
2020-10-30 00:30:59 -07:00
|
|
|
return failure();
|
2024-09-28 18:15:14 -07:00
|
|
|
if (!it->second.isPrinted)
|
|
|
|
return failure();
|
2020-10-30 00:30:59 -07:00
|
|
|
|
2022-11-16 16:26:18 -08:00
|
|
|
it->second.print(os);
|
2020-10-30 00:30:59 -07:00
|
|
|
return success();
|
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
void AliasState::printAliases(AsmPrinter::Impl &p, NewLineCounter &newLine,
|
|
|
|
bool isDeferred) {
|
2020-11-12 23:33:43 -08:00
|
|
|
auto filterFn = [=](const auto &aliasIt) {
|
|
|
|
return aliasIt.second.canBeDeferred() == isDeferred;
|
|
|
|
};
|
2022-11-16 16:26:18 -08:00
|
|
|
for (auto &[opaqueSymbol, alias] :
|
|
|
|
llvm::make_filter_range(attrTypeToAlias, filterFn)) {
|
|
|
|
alias.print(p.getStream());
|
2022-10-22 14:01:41 -07:00
|
|
|
p.getStream() << " = ";
|
|
|
|
|
2022-11-16 16:26:18 -08:00
|
|
|
if (alias.isTypeAlias()) {
|
|
|
|
Type type = Type::getFromOpaquePointer(opaqueSymbol);
|
2024-09-28 18:15:14 -07:00
|
|
|
p.printTypeImpl(type);
|
|
|
|
alias.isPrinted = true;
|
2022-11-16 16:26:18 -08:00
|
|
|
} else {
|
|
|
|
// TODO: Support nested aliases in mutable attributes.
|
|
|
|
Attribute attr = Attribute::getFromOpaquePointer(opaqueSymbol);
|
|
|
|
if (attr.hasTrait<AttributeTrait::IsMutable>())
|
|
|
|
p.getStream() << attr;
|
|
|
|
else
|
|
|
|
p.printAttributeImpl(attr);
|
|
|
|
}
|
2022-10-22 14:01:41 -07:00
|
|
|
|
|
|
|
p.getStream() << newLine;
|
2020-10-30 00:30:59 -07:00
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
2020-01-09 12:39:26 -08:00
|
|
|
// SSANameState
|
2020-01-08 10:11:56 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
2022-02-07 21:10:18 +00:00
|
|
|
/// Info about block printing: a number which is its position in the visitation
|
|
|
|
/// order, and a name that is used to print reference to it, e.g. ^bb42.
|
|
|
|
struct BlockInfo {
|
|
|
|
int ordering;
|
|
|
|
StringRef name;
|
|
|
|
};
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// This class manages the state of SSA value names.
|
|
|
|
class SSANameState {
|
2020-01-08 10:11:56 -08:00
|
|
|
public:
|
2020-01-20 03:14:37 +00:00
|
|
|
/// A sentinel value used for values with names set.
|
2020-01-09 12:39:26 -08:00
|
|
|
enum : unsigned { NameSentinel = ~0U };
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2022-01-21 05:45:48 +00:00
|
|
|
SSANameState(Operation *op, const OpPrintingFlags &printerFlags);
|
2022-09-02 21:23:47 -07:00
|
|
|
SSANameState() = default;
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the SSA identifier for the given value to 'stream'. If
|
|
|
|
/// 'printResultNo' is true, it also presents the result number ('#' number)
|
|
|
|
/// of this value.
|
|
|
|
void printValueID(Value value, bool printResultNo, raw_ostream &stream) const;
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// Print the operation identifier.
|
|
|
|
void printOperationID(Operation *op, raw_ostream &stream) const;
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Return the result indices for each of the result groups registered by this
|
|
|
|
/// operation, or empty if none exist.
|
|
|
|
ArrayRef<int> getOpResultGroups(Operation *op);
|
2019-11-01 14:47:42 -07:00
|
|
|
|
2022-02-07 21:10:18 +00:00
|
|
|
/// Get the info for the given block.
|
|
|
|
BlockInfo getBlockInfo(Block *block);
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Renumber the arguments for the specified region to the same names as the
|
|
|
|
/// SSA values in namesToUse. See OperationPrinter::shadowRegionArgs for
|
|
|
|
/// details.
|
|
|
|
void shadowRegionArgs(Region ®ion, ValueRange namesToUse);
|
2019-06-26 18:29:25 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
private:
|
|
|
|
/// Number the SSA values within the given IR unit.
|
2021-07-10 16:39:34 +00:00
|
|
|
void numberValuesInRegion(Region ®ion);
|
|
|
|
void numberValuesInBlock(Block &block);
|
|
|
|
void numberValuesInOp(Operation &op);
|
2019-02-05 07:12:46 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Given a result of an operation 'result', find the result group head
|
|
|
|
/// 'lookupValue' and the result of 'result' within that group in
|
|
|
|
/// 'lookupResultNo'. 'lookupResultNo' is only filled in if the result group
|
|
|
|
/// has more than 1 result.
|
|
|
|
void getResultIDAndNumber(OpResult result, Value &lookupValue,
|
2023-01-14 01:25:58 -08:00
|
|
|
std::optional<int> &lookupResultNo) const;
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Set a special value name for the given value.
|
|
|
|
void setValueName(Value value, StringRef name);
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Uniques the given value name within the printer. If the given name
|
|
|
|
/// conflicts, it is automatically renamed.
|
|
|
|
StringRef uniqueValueName(StringRef name);
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// This is the value ID for each SSA value. If this returns NameSentinel,
|
|
|
|
/// then the valueID has an entry in valueNames.
|
|
|
|
DenseMap<Value, unsigned> valueIDs;
|
|
|
|
DenseMap<Value, StringRef> valueNames;
|
2019-11-01 14:47:42 -07:00
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// When printing users of values, an operation without a result might
|
|
|
|
/// be the user. This map holds ids for such operations.
|
|
|
|
DenseMap<Operation *, unsigned> operationIDs;
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// This is a map of operations that contain multiple named result groups,
|
|
|
|
/// i.e. there may be multiple names for the results of the operation. The
|
|
|
|
/// value of this map are the result numbers that start a result group.
|
|
|
|
DenseMap<Operation *, SmallVector<int, 1>> opResultGroups;
|
2019-08-21 12:16:23 -07:00
|
|
|
|
2022-02-07 21:10:18 +00:00
|
|
|
/// This maps blocks to there visitation number in the current region as well
|
|
|
|
/// as the string representing their name.
|
|
|
|
DenseMap<Block *, BlockInfo> blockNames;
|
2019-08-21 12:16:23 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// This keeps track of all of the non-numeric names that are in flight,
|
|
|
|
/// allowing us to check for duplicates.
|
|
|
|
/// Note: the value of the map is unused.
|
|
|
|
llvm::ScopedHashTable<StringRef, char> usedNames;
|
|
|
|
llvm::BumpPtrAllocator usedNameAllocator;
|
2019-10-07 13:54:16 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// This is the next value ID to assign in numbering.
|
|
|
|
unsigned nextValueID = 0;
|
|
|
|
/// This is the next ID to assign to a region entry block argument.
|
|
|
|
unsigned nextArgumentID = 0;
|
|
|
|
/// This is the next ID to assign when a name conflict is detected.
|
|
|
|
unsigned nextConflictID = 0;
|
2021-07-10 16:39:34 +00:00
|
|
|
|
2021-07-10 16:39:44 +00:00
|
|
|
/// These are the printing flags. They control, eg., whether to print in
|
|
|
|
/// generic form.
|
|
|
|
OpPrintingFlags printerFlags;
|
2018-07-20 09:35:47 -07:00
|
|
|
};
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2022-07-14 13:31:47 -07:00
|
|
|
SSANameState::SSANameState(Operation *op, const OpPrintingFlags &printerFlags)
|
2022-01-21 05:45:48 +00:00
|
|
|
: printerFlags(printerFlags) {
|
2022-12-02 13:36:04 -08:00
|
|
|
llvm::SaveAndRestore valueIDSaver(nextValueID);
|
|
|
|
llvm::SaveAndRestore argumentIDSaver(nextArgumentID);
|
|
|
|
llvm::SaveAndRestore conflictIDSaver(nextConflictID);
|
2021-05-12 11:21:25 +08:00
|
|
|
|
2021-05-12 14:30:09 -07:00
|
|
|
// The naming context includes `nextValueID`, `nextArgumentID`,
|
|
|
|
// `nextConflictID` and `usedNames` scoped HashTable. This information is
|
|
|
|
// carried from the parent region.
|
|
|
|
using UsedNamesScopeTy = llvm::ScopedHashTable<StringRef, char>::ScopeTy;
|
|
|
|
using NamingContext =
|
|
|
|
std::tuple<Region *, unsigned, unsigned, unsigned, UsedNamesScopeTy *>;
|
|
|
|
|
|
|
|
// Allocator for UsedNamesScopeTy
|
2021-05-12 11:21:25 +08:00
|
|
|
llvm::BumpPtrAllocator allocator;
|
|
|
|
|
2021-05-12 14:30:09 -07:00
|
|
|
// Add a scope for the top level operation.
|
|
|
|
auto *topLevelNamesScope =
|
|
|
|
new (allocator.Allocate<UsedNamesScopeTy>()) UsedNamesScopeTy(usedNames);
|
|
|
|
|
|
|
|
SmallVector<NamingContext, 8> nameContext;
|
2021-05-12 11:21:25 +08:00
|
|
|
for (Region ®ion : op->getRegions())
|
|
|
|
nameContext.push_back(std::make_tuple(®ion, nextValueID, nextArgumentID,
|
2021-05-12 14:30:09 -07:00
|
|
|
nextConflictID, topLevelNamesScope));
|
2021-05-12 11:21:25 +08:00
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
numberValuesInOp(*op);
|
2019-01-23 13:11:23 -08:00
|
|
|
|
2021-05-12 11:21:25 +08:00
|
|
|
while (!nameContext.empty()) {
|
|
|
|
Region *region;
|
2021-05-12 14:30:09 -07:00
|
|
|
UsedNamesScopeTy *parentScope;
|
2024-05-07 10:45:28 -05:00
|
|
|
|
|
|
|
if (printerFlags.shouldPrintUniqueSSAIDs())
|
|
|
|
// To print unique SSA IDs, ignore saved ID counts from parent regions
|
|
|
|
std::tie(region, std::ignore, std::ignore, std::ignore, parentScope) =
|
|
|
|
nameContext.pop_back_val();
|
|
|
|
else
|
|
|
|
std::tie(region, nextValueID, nextArgumentID, nextConflictID,
|
|
|
|
parentScope) = nameContext.pop_back_val();
|
2021-05-12 11:21:25 +08:00
|
|
|
|
|
|
|
// When we switch from one subtree to another, pop the scopes(needless)
|
|
|
|
// until the parent scope.
|
|
|
|
while (usedNames.getCurScope() != parentScope) {
|
2021-05-12 14:30:09 -07:00
|
|
|
usedNames.getCurScope()->~UsedNamesScopeTy();
|
2021-05-12 11:21:25 +08:00
|
|
|
assert((usedNames.getCurScope() != nullptr || parentScope == nullptr) &&
|
|
|
|
"top level parentScope must be a nullptr");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add a scope for the current region.
|
2021-05-12 14:30:09 -07:00
|
|
|
auto *curNamesScope = new (allocator.Allocate<UsedNamesScopeTy>())
|
|
|
|
UsedNamesScopeTy(usedNames);
|
2021-05-12 11:21:25 +08:00
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
numberValuesInRegion(*region);
|
2021-05-12 11:21:25 +08:00
|
|
|
|
2021-05-12 14:30:09 -07:00
|
|
|
for (Operation &op : region->getOps())
|
|
|
|
for (Region ®ion : op.getRegions())
|
|
|
|
nameContext.push_back(std::make_tuple(®ion, nextValueID,
|
|
|
|
nextArgumentID, nextConflictID,
|
|
|
|
curNamesScope));
|
2021-05-12 11:21:25 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Manually remove all the scopes.
|
|
|
|
while (usedNames.getCurScope() != nullptr)
|
2021-05-12 14:30:09 -07:00
|
|
|
usedNames.getCurScope()->~UsedNamesScopeTy();
|
2019-01-23 13:11:23 -08:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void SSANameState::printValueID(Value value, bool printResultNo,
|
|
|
|
raw_ostream &stream) const {
|
|
|
|
if (!value) {
|
2022-01-04 08:12:51 +05:30
|
|
|
stream << "<<NULL VALUE>>";
|
2020-01-09 12:39:26 -08:00
|
|
|
return;
|
2019-01-23 13:11:23 -08:00
|
|
|
}
|
|
|
|
|
2023-01-14 01:25:58 -08:00
|
|
|
std::optional<int> resultNo;
|
2020-01-09 12:39:26 -08:00
|
|
|
auto lookupValue = value;
|
2018-08-15 09:09:54 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// If this is an operation result, collect the head lookup value of the result
|
|
|
|
// group and the result number of 'result' within that group.
|
2022-10-14 11:56:35 -05:00
|
|
|
if (OpResult result = dyn_cast<OpResult>(value))
|
2020-01-09 12:39:26 -08:00
|
|
|
getResultIDAndNumber(result, lookupValue, resultNo);
|
2019-07-30 14:05:49 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
auto it = valueIDs.find(lookupValue);
|
|
|
|
if (it == valueIDs.end()) {
|
|
|
|
stream << "<<UNKNOWN SSA VALUE>>";
|
2019-07-30 14:05:49 -07:00
|
|
|
return;
|
2018-08-15 09:09:54 -07:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
stream << '%';
|
|
|
|
if (it->second != NameSentinel) {
|
|
|
|
stream << it->second;
|
2019-01-25 20:37:33 -08:00
|
|
|
} else {
|
2020-01-09 12:39:26 -08:00
|
|
|
auto nameIt = valueNames.find(lookupValue);
|
|
|
|
assert(nameIt != valueNames.end() && "Didn't have a name entry?");
|
|
|
|
stream << nameIt->second;
|
2019-01-25 20:37:33 -08:00
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2022-06-20 11:22:37 -07:00
|
|
|
if (resultNo && printResultNo)
|
2022-12-16 19:57:30 +00:00
|
|
|
stream << '#' << *resultNo;
|
2019-01-23 13:11:23 -08:00
|
|
|
}
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
void SSANameState::printOperationID(Operation *op, raw_ostream &stream) const {
|
|
|
|
auto it = operationIDs.find(op);
|
|
|
|
if (it == operationIDs.end()) {
|
2023-03-23 09:50:40 +09:00
|
|
|
stream << "<<UNKNOWN OPERATION>>";
|
2022-04-22 18:52:54 +00:00
|
|
|
} else {
|
|
|
|
stream << '%' << it->second;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
ArrayRef<int> SSANameState::getOpResultGroups(Operation *op) {
|
|
|
|
auto it = opResultGroups.find(op);
|
|
|
|
return it == opResultGroups.end() ? ArrayRef<int>() : it->second;
|
|
|
|
}
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2022-02-07 21:10:18 +00:00
|
|
|
BlockInfo SSANameState::getBlockInfo(Block *block) {
|
|
|
|
auto it = blockNames.find(block);
|
|
|
|
BlockInfo invalidBlock{-1, "INVALIDBLOCK"};
|
|
|
|
return it != blockNames.end() ? it->second : invalidBlock;
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void SSANameState::shadowRegionArgs(Region ®ion, ValueRange namesToUse) {
|
|
|
|
assert(!region.empty() && "cannot shadow arguments of an empty region");
|
2020-07-10 17:07:29 -07:00
|
|
|
assert(region.getNumArguments() == namesToUse.size() &&
|
2020-01-09 12:39:26 -08:00
|
|
|
"incorrect number of names passed in");
|
2021-02-09 11:41:10 -08:00
|
|
|
assert(region.getParentOp()->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
|
2020-01-09 12:39:26 -08:00
|
|
|
"only KnownIsolatedFromAbove ops can shadow names");
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
SmallVector<char, 16> nameStr;
|
|
|
|
for (unsigned i = 0, e = namesToUse.size(); i != e; ++i) {
|
|
|
|
auto nameToUse = namesToUse[i];
|
|
|
|
if (nameToUse == nullptr)
|
2019-05-15 09:10:52 -07:00
|
|
|
continue;
|
2020-07-10 17:07:29 -07:00
|
|
|
auto nameToReplace = region.getArgument(i);
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
nameStr.clear();
|
|
|
|
llvm::raw_svector_ostream nameStream(nameStr);
|
|
|
|
printValueID(nameToUse, /*printResultNo=*/true, nameStream);
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Entry block arguments should already have a pretty "arg" name.
|
|
|
|
assert(valueIDs[nameToReplace] == NameSentinel);
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Use the name without the leading %.
|
|
|
|
auto name = StringRef(nameStream.str()).drop_front();
|
2019-05-15 09:10:52 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Overwrite the name.
|
|
|
|
valueNames[nameToReplace] = name.copy(usedNameAllocator);
|
2019-05-15 09:10:52 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-12-17 07:59:11 -08:00
|
|
|
namespace {
|
|
|
|
/// Try to get value name from value's location, fallback to `name`.
|
|
|
|
StringRef maybeGetValueNameFromLoc(Value value, StringRef name) {
|
|
|
|
if (auto maybeNameLoc = value.getLoc()->findInstanceOf<NameLoc>())
|
|
|
|
return maybeNameLoc.getName();
|
|
|
|
return name;
|
|
|
|
}
|
|
|
|
} // namespace
|
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
void SSANameState::numberValuesInRegion(Region ®ion) {
|
2025-02-19 02:07:17 +08:00
|
|
|
// Indicates whether OpAsmOpInterface set a name.
|
|
|
|
bool opAsmOpInterfaceUsed = false;
|
2021-12-20 07:17:26 +00:00
|
|
|
auto setBlockArgNameFn = [&](Value arg, StringRef name) {
|
|
|
|
assert(!valueIDs.count(arg) && "arg numbered multiple times");
|
2023-05-11 11:10:46 +02:00
|
|
|
assert(llvm::cast<BlockArgument>(arg).getOwner()->getParent() == ®ion &&
|
2021-12-20 07:17:26 +00:00
|
|
|
"arg not defined in current region");
|
2025-02-19 02:07:17 +08:00
|
|
|
opAsmOpInterfaceUsed = true;
|
2024-12-17 07:59:11 -08:00
|
|
|
if (LLVM_UNLIKELY(printerFlags.shouldUseNameLocAsPrefix()))
|
|
|
|
name = maybeGetValueNameFromLoc(arg, name);
|
2021-12-20 07:17:26 +00:00
|
|
|
setValueName(arg, name);
|
|
|
|
};
|
|
|
|
|
|
|
|
if (!printerFlags.shouldPrintGenericOpForm()) {
|
|
|
|
if (Operation *op = region.getParentOp()) {
|
|
|
|
if (auto asmInterface = dyn_cast<OpAsmOpInterface>(op))
|
|
|
|
asmInterface.getAsmBlockArgumentNames(region, setBlockArgNameFn);
|
2025-02-19 02:07:17 +08:00
|
|
|
// If the OpAsmOpInterface didn't set a name, get name from the type.
|
|
|
|
if (!opAsmOpInterfaceUsed) {
|
|
|
|
for (BlockArgument arg : region.getArguments()) {
|
|
|
|
if (auto interface = dyn_cast<OpAsmTypeInterface>(arg.getType())) {
|
|
|
|
interface.getAsmName(
|
|
|
|
[&](StringRef name) { setBlockArgNameFn(arg, name); });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-12-20 07:17:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Number the values within this region in a breadth-first order.
|
|
|
|
unsigned nextBlockID = 0;
|
|
|
|
for (auto &block : region) {
|
|
|
|
// Each block gets a unique ID, and all of the operations within it get
|
|
|
|
// numbered as well.
|
2022-02-07 21:10:18 +00:00
|
|
|
auto blockInfoIt = blockNames.insert({&block, {-1, ""}});
|
|
|
|
if (blockInfoIt.second) {
|
|
|
|
// This block hasn't been named through `getAsmBlockArgumentNames`, use
|
|
|
|
// default `^bbNNN` format.
|
|
|
|
std::string name;
|
|
|
|
llvm::raw_string_ostream(name) << "^bb" << nextBlockID;
|
|
|
|
blockInfoIt.first->second.name = StringRef(name).copy(usedNameAllocator);
|
|
|
|
}
|
|
|
|
blockInfoIt.first->second.ordering = nextBlockID++;
|
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
numberValuesInBlock(block);
|
2019-10-08 17:44:39 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
void SSANameState::numberValuesInBlock(Block &block) {
|
2020-01-09 12:39:26 -08:00
|
|
|
// Number the block arguments. We give entry block arguments a special name
|
|
|
|
// 'arg'.
|
2021-12-20 07:17:26 +00:00
|
|
|
bool isEntryBlock = block.isEntryBlock();
|
2020-01-09 12:39:26 -08:00
|
|
|
SmallString<32> specialNameBuffer(isEntryBlock ? "arg" : "");
|
|
|
|
llvm::raw_svector_ostream specialName(specialNameBuffer);
|
|
|
|
for (auto arg : block.getArguments()) {
|
|
|
|
if (valueIDs.count(arg))
|
|
|
|
continue;
|
|
|
|
if (isEntryBlock) {
|
|
|
|
specialNameBuffer.resize(strlen("arg"));
|
|
|
|
specialName << nextArgumentID++;
|
2019-08-21 12:16:23 -07:00
|
|
|
}
|
2024-12-17 07:59:11 -08:00
|
|
|
StringRef specialNameStr = specialName.str();
|
|
|
|
if (LLVM_UNLIKELY(printerFlags.shouldUseNameLocAsPrefix()))
|
|
|
|
specialNameStr = maybeGetValueNameFromLoc(arg, specialNameStr);
|
|
|
|
setValueName(arg, specialNameStr);
|
2019-05-06 10:36:32 -07:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Number the operations in this block.
|
|
|
|
for (auto &op : block)
|
2021-07-10 16:39:34 +00:00
|
|
|
numberValuesInOp(op);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
2019-06-26 18:29:25 -07:00
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
void SSANameState::numberValuesInOp(Operation &op) {
|
2020-01-09 12:39:26 -08:00
|
|
|
// Function used to set the special result names for the operation.
|
|
|
|
SmallVector<int, 2> resultGroups(/*Size=*/1, /*Value=*/0);
|
2025-02-19 02:07:17 +08:00
|
|
|
// Indicates whether OpAsmOpInterface set a name.
|
|
|
|
bool opAsmOpInterfaceUsed = false;
|
2020-01-09 12:39:26 -08:00
|
|
|
auto setResultNameFn = [&](Value result, StringRef name) {
|
|
|
|
assert(!valueIDs.count(result) && "result numbered multiple times");
|
2020-01-11 08:54:04 -08:00
|
|
|
assert(result.getDefiningOp() == &op && "result not defined by 'op'");
|
2025-02-19 02:07:17 +08:00
|
|
|
opAsmOpInterfaceUsed = true;
|
2024-12-17 07:59:11 -08:00
|
|
|
if (LLVM_UNLIKELY(printerFlags.shouldUseNameLocAsPrefix()))
|
|
|
|
name = maybeGetValueNameFromLoc(result, name);
|
2020-01-09 12:39:26 -08:00
|
|
|
setValueName(result, name);
|
2019-10-21 11:01:38 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Record the result number for groups not anchored at 0.
|
2023-05-11 11:10:46 +02:00
|
|
|
if (int resultNo = llvm::cast<OpResult>(result).getResultNumber())
|
2020-01-09 12:39:26 -08:00
|
|
|
resultGroups.push_back(resultNo);
|
|
|
|
};
|
2022-02-07 21:10:18 +00:00
|
|
|
// Operations can customize the printing of block names in OpAsmOpInterface.
|
|
|
|
auto setBlockNameFn = [&](Block *block, StringRef name) {
|
|
|
|
assert(block->getParentOp() == &op &&
|
|
|
|
"getAsmBlockArgumentNames callback invoked on a block not directly "
|
|
|
|
"nested under the current operation");
|
|
|
|
assert(!blockNames.count(block) && "block numbered multiple times");
|
|
|
|
SmallString<16> tmpBuffer{"^"};
|
|
|
|
name = sanitizeIdentifier(name, tmpBuffer);
|
|
|
|
if (name.data() != tmpBuffer.data()) {
|
|
|
|
tmpBuffer.append(name);
|
|
|
|
name = tmpBuffer.str();
|
|
|
|
}
|
|
|
|
name = name.copy(usedNameAllocator);
|
|
|
|
blockNames[block] = {-1, name};
|
|
|
|
};
|
|
|
|
|
2021-07-10 16:39:50 +00:00
|
|
|
if (!printerFlags.shouldPrintGenericOpForm()) {
|
2022-02-07 21:10:18 +00:00
|
|
|
if (OpAsmOpInterface asmInterface = dyn_cast<OpAsmOpInterface>(&op)) {
|
|
|
|
asmInterface.getAsmBlockNames(setBlockNameFn);
|
2021-07-10 16:39:50 +00:00
|
|
|
asmInterface.getAsmResultNames(setResultNameFn);
|
2022-02-07 21:10:18 +00:00
|
|
|
}
|
2025-02-19 02:07:17 +08:00
|
|
|
if (!opAsmOpInterfaceUsed) {
|
|
|
|
// If the OpAsmOpInterface didn't set a name, and all results have
|
|
|
|
// OpAsmTypeInterface, get names from types.
|
|
|
|
bool allHaveOpAsmTypeInterface =
|
|
|
|
llvm::all_of(op.getResultTypes(), [&](Type type) {
|
|
|
|
return isa<OpAsmTypeInterface>(type);
|
|
|
|
});
|
|
|
|
if (allHaveOpAsmTypeInterface) {
|
|
|
|
for (OpResult result : op.getResults()) {
|
|
|
|
auto interface = cast<OpAsmTypeInterface>(result.getType());
|
|
|
|
interface.getAsmName(
|
|
|
|
[&](StringRef name) { setResultNameFn(result, name); });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-07-10 16:39:50 +00:00
|
|
|
}
|
2019-06-26 18:29:25 -07:00
|
|
|
|
2022-02-07 21:10:18 +00:00
|
|
|
unsigned numResults = op.getNumResults();
|
2022-04-22 18:52:54 +00:00
|
|
|
if (numResults == 0) {
|
|
|
|
// If value users should be printed, operations with no result need an id.
|
|
|
|
if (printerFlags.shouldPrintValueUsers()) {
|
|
|
|
if (operationIDs.try_emplace(&op, nextValueID).second)
|
|
|
|
++nextValueID;
|
|
|
|
}
|
2022-02-07 21:10:18 +00:00
|
|
|
return;
|
2022-04-22 18:52:54 +00:00
|
|
|
}
|
2022-02-07 21:10:18 +00:00
|
|
|
Value resultBegin = op.getResult(0);
|
|
|
|
|
2024-12-17 07:59:11 -08:00
|
|
|
if (printerFlags.shouldUseNameLocAsPrefix() && !valueIDs.count(resultBegin)) {
|
|
|
|
if (auto nameLoc = resultBegin.getLoc()->findInstanceOf<NameLoc>()) {
|
|
|
|
setValueName(resultBegin, nameLoc.getName());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// If the first result wasn't numbered, give it a default number.
|
|
|
|
if (valueIDs.try_emplace(resultBegin, nextValueID).second)
|
|
|
|
++nextValueID;
|
2019-06-26 18:29:25 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// If this operation has multiple result groups, mark it.
|
|
|
|
if (resultGroups.size() != 1) {
|
|
|
|
llvm::array_pod_sort(resultGroups.begin(), resultGroups.end());
|
|
|
|
opResultGroups.try_emplace(&op, std::move(resultGroups));
|
2019-02-05 07:12:46 -08:00
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
2023-01-14 01:25:58 -08:00
|
|
|
void SSANameState::getResultIDAndNumber(
|
|
|
|
OpResult result, Value &lookupValue,
|
|
|
|
std::optional<int> &lookupResultNo) const {
|
2020-01-11 08:54:04 -08:00
|
|
|
Operation *owner = result.getOwner();
|
2020-01-09 12:39:26 -08:00
|
|
|
if (owner->getNumResults() == 1)
|
|
|
|
return;
|
2020-01-11 08:54:04 -08:00
|
|
|
int resultNo = result.getResultNumber();
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
// If this operation has multiple result groups, we will need to find the
|
|
|
|
// one corresponding to this result.
|
|
|
|
auto resultGroupIt = opResultGroups.find(owner);
|
|
|
|
if (resultGroupIt == opResultGroups.end()) {
|
|
|
|
// If not, just use the first result.
|
|
|
|
lookupResultNo = resultNo;
|
|
|
|
lookupValue = owner->getResult(0);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find the correct index using a binary search, as the groups are ordered.
|
|
|
|
ArrayRef<int> resultGroups = resultGroupIt->second;
|
2021-12-20 19:45:05 +00:00
|
|
|
const auto *it = llvm::upper_bound(resultGroups, resultNo);
|
2020-01-09 12:39:26 -08:00
|
|
|
int groupResultNo = 0, groupSize = 0;
|
|
|
|
|
|
|
|
// If there are no smaller elements, the last result group is the lookup.
|
|
|
|
if (it == resultGroups.end()) {
|
|
|
|
groupResultNo = resultGroups.back();
|
|
|
|
groupSize = static_cast<int>(owner->getNumResults()) - resultGroups.back();
|
|
|
|
} else {
|
|
|
|
// Otherwise, the previous element is the lookup.
|
|
|
|
groupResultNo = *std::prev(it);
|
|
|
|
groupSize = *it - groupResultNo;
|
|
|
|
}
|
|
|
|
|
|
|
|
// We only record the result number for a group of size greater than 1.
|
|
|
|
if (groupSize != 1)
|
|
|
|
lookupResultNo = resultNo - groupResultNo;
|
|
|
|
lookupValue = owner->getResult(groupResultNo);
|
|
|
|
}
|
|
|
|
|
|
|
|
void SSANameState::setValueName(Value value, StringRef name) {
|
|
|
|
// If the name is empty, the value uses the default numbering.
|
|
|
|
if (name.empty()) {
|
|
|
|
valueIDs[value] = nextValueID++;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
valueIDs[value] = NameSentinel;
|
|
|
|
valueNames[value] = uniqueValueName(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
StringRef SSANameState::uniqueValueName(StringRef name) {
|
2020-10-30 00:30:59 -07:00
|
|
|
SmallString<16> tmpBuffer;
|
|
|
|
name = sanitizeIdentifier(name, tmpBuffer);
|
Add support for custom op parser/printer hooks to know about result names.
Summary:
This allows the custom parser/printer hooks to do interesting things with
the SSA names. This patch:
- Adds a new 'getResultName' method to OpAsmParser that allows a parser
implementation to get information about its result names, along with
a getNumResults() method that allows op parser impls to know how many
results are expected.
- Adds a OpAsmPrinter::printOperand overload that takes an explicit stream.
- Adds a test.string_attr_pretty_name operation that uses these hooks to
do fancy things with the result name.
Reviewers: rriddle!
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76205
2020-03-15 17:13:59 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Check to see if this name is already unique.
|
|
|
|
if (!usedNames.count(name)) {
|
|
|
|
name = name.copy(usedNameAllocator);
|
|
|
|
} else {
|
|
|
|
// Otherwise, we had a conflict - probe until we find a unique name. This
|
|
|
|
// is guaranteed to terminate (and usually in a single iteration) because it
|
|
|
|
// generates new names by incrementing nextConflictID.
|
|
|
|
SmallString<64> probeName(name);
|
|
|
|
probeName.push_back('_');
|
|
|
|
while (true) {
|
|
|
|
probeName += llvm::utostr(nextConflictID++);
|
|
|
|
if (!usedNames.count(probeName)) {
|
2021-07-08 13:30:14 -07:00
|
|
|
name = probeName.str().copy(usedNameAllocator);
|
2020-01-09 12:39:26 -08:00
|
|
|
break;
|
|
|
|
}
|
2020-10-30 00:30:59 -07:00
|
|
|
probeName.resize(name.size() + 1);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
usedNames.insert(name, char());
|
|
|
|
return name;
|
|
|
|
}
|
|
|
|
|
2023-07-11 07:30:18 +00:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// DistinctState
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
/// This class manages the state for distinct attributes.
|
|
|
|
class DistinctState {
|
|
|
|
public:
|
|
|
|
/// Returns a unique identifier for the given distinct attribute.
|
|
|
|
uint64_t getId(DistinctAttr distinctAttr);
|
|
|
|
|
|
|
|
private:
|
|
|
|
uint64_t distinctCounter = 0;
|
|
|
|
DenseMap<DistinctAttr, uint64_t> distinctAttrMap;
|
|
|
|
};
|
|
|
|
} // namespace
|
|
|
|
|
|
|
|
uint64_t DistinctState::getId(DistinctAttr distinctAttr) {
|
|
|
|
auto [it, inserted] =
|
|
|
|
distinctAttrMap.try_emplace(distinctAttr, distinctCounter);
|
|
|
|
if (inserted)
|
|
|
|
distinctCounter++;
|
|
|
|
return it->getSecond();
|
|
|
|
}
|
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Resources
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
AsmParsedResourceEntry::~AsmParsedResourceEntry() = default;
|
|
|
|
AsmResourceBuilder::~AsmResourceBuilder() = default;
|
|
|
|
AsmResourceParser::~AsmResourceParser() = default;
|
|
|
|
AsmResourcePrinter::~AsmResourcePrinter() = default;
|
|
|
|
|
2022-09-06 20:47:57 -07:00
|
|
|
StringRef mlir::toString(AsmResourceEntryKind kind) {
|
|
|
|
switch (kind) {
|
|
|
|
case AsmResourceEntryKind::Blob:
|
|
|
|
return "blob";
|
|
|
|
case AsmResourceEntryKind::Bool:
|
|
|
|
return "bool";
|
|
|
|
case AsmResourceEntryKind::String:
|
|
|
|
return "string";
|
|
|
|
}
|
|
|
|
llvm_unreachable("unknown AsmResourceEntryKind");
|
|
|
|
}
|
|
|
|
|
2022-09-13 01:07:29 -07:00
|
|
|
AsmResourceParser &FallbackAsmResourceMap::getParserFor(StringRef key) {
|
|
|
|
std::unique_ptr<ResourceCollection> &collection = keyToResources[key.str()];
|
|
|
|
if (!collection)
|
|
|
|
collection = std::make_unique<ResourceCollection>(key);
|
|
|
|
return *collection;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<std::unique_ptr<AsmResourcePrinter>>
|
|
|
|
FallbackAsmResourceMap::getPrinters() {
|
|
|
|
std::vector<std::unique_ptr<AsmResourcePrinter>> printers;
|
|
|
|
for (auto &it : keyToResources) {
|
|
|
|
ResourceCollection *collection = it.second.get();
|
|
|
|
auto buildValues = [=](Operation *op, AsmResourceBuilder &builder) {
|
|
|
|
return collection->buildResources(op, builder);
|
|
|
|
};
|
|
|
|
printers.emplace_back(
|
|
|
|
AsmResourcePrinter::fromCallable(collection->getName(), buildValues));
|
|
|
|
}
|
|
|
|
return printers;
|
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult FallbackAsmResourceMap::ResourceCollection::parseResource(
|
|
|
|
AsmParsedResourceEntry &entry) {
|
|
|
|
switch (entry.getKind()) {
|
|
|
|
case AsmResourceEntryKind::Blob: {
|
|
|
|
FailureOr<AsmResourceBlob> blob = entry.parseAsBlob();
|
|
|
|
if (failed(blob))
|
|
|
|
return failure();
|
|
|
|
resources.emplace_back(entry.getKey(), std::move(*blob));
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
case AsmResourceEntryKind::Bool: {
|
|
|
|
FailureOr<bool> value = entry.parseAsBool();
|
|
|
|
if (failed(value))
|
|
|
|
return failure();
|
|
|
|
resources.emplace_back(entry.getKey(), *value);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
case AsmResourceEntryKind::String: {
|
|
|
|
FailureOr<std::string> str = entry.parseAsString();
|
|
|
|
if (failed(str))
|
|
|
|
return failure();
|
|
|
|
resources.emplace_back(entry.getKey(), std::move(*str));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
void FallbackAsmResourceMap::ResourceCollection::buildResources(
|
|
|
|
Operation *op, AsmResourceBuilder &builder) const {
|
|
|
|
for (const auto &entry : resources) {
|
|
|
|
if (const auto *value = std::get_if<AsmResourceBlob>(&entry.value))
|
|
|
|
builder.buildBlob(entry.key, *value);
|
|
|
|
else if (const auto *value = std::get_if<bool>(&entry.value))
|
|
|
|
builder.buildBool(entry.key, *value);
|
|
|
|
else if (const auto *value = std::get_if<std::string>(&entry.value))
|
|
|
|
builder.buildString(entry.key, *value);
|
|
|
|
else
|
|
|
|
llvm_unreachable("unknown AsmResourceEntryKind");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2020-01-14 15:23:05 -08:00
|
|
|
// AsmState
|
2020-01-09 12:39:26 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2020-01-14 15:23:05 -08:00
|
|
|
namespace mlir {
|
|
|
|
namespace detail {
|
|
|
|
class AsmStateImpl {
|
2020-01-09 12:39:26 -08:00
|
|
|
public:
|
2021-07-10 16:39:44 +00:00
|
|
|
explicit AsmStateImpl(Operation *op, const OpPrintingFlags &printerFlags,
|
|
|
|
AsmState::LocationMap *locationMap)
|
2022-01-21 05:45:48 +00:00
|
|
|
: interfaces(op->getContext()), nameState(op, printerFlags),
|
2021-07-10 16:39:44 +00:00
|
|
|
printerFlags(printerFlags), locationMap(locationMap) {}
|
2022-09-02 21:23:47 -07:00
|
|
|
explicit AsmStateImpl(MLIRContext *ctx, const OpPrintingFlags &printerFlags,
|
|
|
|
AsmState::LocationMap *locationMap)
|
|
|
|
: interfaces(ctx), printerFlags(printerFlags), locationMap(locationMap) {}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
/// Initialize the alias state to enable the printing of aliases.
|
2021-07-10 16:39:44 +00:00
|
|
|
void initializeAliases(Operation *op) {
|
2020-11-09 21:50:31 -08:00
|
|
|
aliasState.initialize(op, printerFlags, interfaces);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the state used for aliases.
|
|
|
|
AliasState &getAliasState() { return aliasState; }
|
|
|
|
|
|
|
|
/// Get the state used for SSA names.
|
|
|
|
SSANameState &getSSANameState() { return nameState; }
|
|
|
|
|
2023-07-11 07:30:18 +00:00
|
|
|
/// Get the state used for distinct attribute identifiers.
|
|
|
|
DistinctState &getDistinctState() { return distinctState; }
|
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
/// Return the dialects within the context that implement
|
|
|
|
/// OpAsmDialectInterface.
|
|
|
|
DialectInterfaceCollection<OpAsmDialectInterface> &getDialectInterfaces() {
|
|
|
|
return interfaces;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the non-dialect resource printers.
|
|
|
|
auto getResourcePrinters() {
|
|
|
|
return llvm::make_pointee_range(externalResourcePrinters);
|
|
|
|
}
|
|
|
|
|
2022-02-15 17:09:08 -08:00
|
|
|
/// Get the printer flags.
|
|
|
|
const OpPrintingFlags &getPrinterFlags() const { return printerFlags; }
|
|
|
|
|
2020-02-08 15:01:34 -08:00
|
|
|
/// Register the location, line and column, within the buffer that the given
|
|
|
|
/// operation was printed at.
|
|
|
|
void registerOperationLocation(Operation *op, unsigned line, unsigned col) {
|
|
|
|
if (locationMap)
|
|
|
|
(*locationMap)[op] = std::make_pair(line, col);
|
|
|
|
}
|
|
|
|
|
2022-09-02 21:23:47 -07:00
|
|
|
/// Return the referenced dialect resources within the printer.
|
|
|
|
DenseMap<Dialect *, SetVector<AsmDialectResourceHandle>> &
|
|
|
|
getDialectResources() {
|
|
|
|
return dialectResources;
|
|
|
|
}
|
|
|
|
|
2023-09-04 18:19:18 +02:00
|
|
|
LogicalResult pushCyclicPrinting(const void *opaquePointer) {
|
|
|
|
return success(cyclicPrintingStack.insert(opaquePointer));
|
|
|
|
}
|
|
|
|
|
|
|
|
void popCyclicPrinting() { cyclicPrintingStack.pop_back(); }
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
private:
|
|
|
|
/// Collection of OpAsm interfaces implemented in the context.
|
|
|
|
DialectInterfaceCollection<OpAsmDialectInterface> interfaces;
|
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
/// A collection of non-dialect resource printers.
|
|
|
|
SmallVector<std::unique_ptr<AsmResourcePrinter>> externalResourcePrinters;
|
|
|
|
|
2022-09-02 21:23:47 -07:00
|
|
|
/// A set of dialect resources that were referenced during printing.
|
|
|
|
DenseMap<Dialect *, SetVector<AsmDialectResourceHandle>> dialectResources;
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// The state used for attribute and type aliases.
|
|
|
|
AliasState aliasState;
|
|
|
|
|
|
|
|
/// The state used for SSA value names.
|
|
|
|
SSANameState nameState;
|
2020-02-08 15:01:34 -08:00
|
|
|
|
2023-07-11 07:30:18 +00:00
|
|
|
/// The state used for distinct attribute identifiers.
|
|
|
|
DistinctState distinctState;
|
|
|
|
|
2021-07-10 16:39:44 +00:00
|
|
|
/// Flags that control op output.
|
|
|
|
OpPrintingFlags printerFlags;
|
|
|
|
|
2020-02-08 15:01:34 -08:00
|
|
|
/// An optional location map to be populated.
|
|
|
|
AsmState::LocationMap *locationMap;
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
|
2023-09-04 18:19:18 +02:00
|
|
|
/// Stack of potentially cyclic mutable attributes or type currently being
|
|
|
|
/// printed.
|
|
|
|
SetVector<const void *> cyclicPrintingStack;
|
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
// Allow direct access to the impl fields.
|
|
|
|
friend AsmState;
|
2020-01-09 12:39:26 -08:00
|
|
|
};
|
2023-12-08 11:34:44 -08:00
|
|
|
|
|
|
|
template <typename Range>
|
|
|
|
void printDimensionList(raw_ostream &stream, Range &&shape) {
|
|
|
|
llvm::interleave(
|
|
|
|
shape, stream,
|
|
|
|
[&stream](const auto &dimSize) {
|
|
|
|
if (ShapedType::isDynamic(dimSize))
|
|
|
|
stream << "?";
|
|
|
|
else
|
|
|
|
stream << dimSize;
|
|
|
|
},
|
|
|
|
"x");
|
|
|
|
}
|
|
|
|
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace detail
|
|
|
|
} // namespace mlir
|
2020-01-14 15:23:05 -08:00
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
/// Verifies the operation and switches to generic op printing if verification
|
|
|
|
/// fails. We need to do this because custom print functions may fail for
|
|
|
|
/// invalid ops.
|
|
|
|
static OpPrintingFlags verifyOpAndAdjustFlags(Operation *op,
|
|
|
|
OpPrintingFlags printerFlags) {
|
|
|
|
if (printerFlags.shouldPrintGenericOpForm() ||
|
|
|
|
printerFlags.shouldAssumeVerified())
|
|
|
|
return printerFlags;
|
|
|
|
|
|
|
|
// Ignore errors emitted by the verifier. We check the thread id to avoid
|
|
|
|
// consuming other threads' errors.
|
|
|
|
auto parentThreadId = llvm::get_threadid();
|
2022-05-10 22:48:46 +00:00
|
|
|
ScopedDiagnosticHandler diagHandler(op->getContext(), [&](Diagnostic &diag) {
|
|
|
|
if (parentThreadId == llvm::get_threadid()) {
|
|
|
|
LLVM_DEBUG({
|
|
|
|
diag.print(llvm::dbgs());
|
|
|
|
llvm::dbgs() << "\n";
|
|
|
|
});
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
return failure();
|
2022-03-07 07:49:46 -08:00
|
|
|
});
|
2022-05-10 22:48:46 +00:00
|
|
|
if (failed(verify(op))) {
|
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
|
|
|
<< DEBUG_TYPE << ": '" << op->getName()
|
|
|
|
<< "' failed to verify and will be printed in generic form\n");
|
2022-03-07 07:49:46 -08:00
|
|
|
printerFlags.printGenericOpForm();
|
2022-05-10 22:48:46 +00:00
|
|
|
}
|
2022-03-07 07:49:46 -08:00
|
|
|
|
|
|
|
return printerFlags;
|
|
|
|
}
|
|
|
|
|
2021-07-10 16:39:44 +00:00
|
|
|
AsmState::AsmState(Operation *op, const OpPrintingFlags &printerFlags,
|
2022-09-13 01:07:29 -07:00
|
|
|
LocationMap *locationMap, FallbackAsmResourceMap *map)
|
2022-03-07 07:49:46 -08:00
|
|
|
: impl(std::make_unique<AsmStateImpl>(
|
2022-09-13 01:07:29 -07:00
|
|
|
op, verifyOpAndAdjustFlags(op, printerFlags), locationMap)) {
|
|
|
|
if (map)
|
|
|
|
attachFallbackResourcePrinter(*map);
|
|
|
|
}
|
2022-09-02 21:23:47 -07:00
|
|
|
AsmState::AsmState(MLIRContext *ctx, const OpPrintingFlags &printerFlags,
|
2022-09-13 01:07:29 -07:00
|
|
|
LocationMap *locationMap, FallbackAsmResourceMap *map)
|
|
|
|
: impl(std::make_unique<AsmStateImpl>(ctx, printerFlags, locationMap)) {
|
|
|
|
if (map)
|
|
|
|
attachFallbackResourcePrinter(*map);
|
|
|
|
}
|
2021-12-22 00:19:53 +00:00
|
|
|
AsmState::~AsmState() = default;
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2022-02-15 17:09:08 -08:00
|
|
|
const OpPrintingFlags &AsmState::getPrinterFlags() const {
|
|
|
|
return impl->getPrinterFlags();
|
|
|
|
}
|
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
void AsmState::attachResourcePrinter(
|
|
|
|
std::unique_ptr<AsmResourcePrinter> printer) {
|
|
|
|
impl->externalResourcePrinters.emplace_back(std::move(printer));
|
|
|
|
}
|
|
|
|
|
2022-09-02 21:23:47 -07:00
|
|
|
DenseMap<Dialect *, SetVector<AsmDialectResourceHandle>> &
|
|
|
|
AsmState::getDialectResources() const {
|
|
|
|
return impl->getDialectResources();
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2021-09-24 19:56:01 +00:00
|
|
|
// AsmPrinter::Impl
|
2020-01-09 12:39:26 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
AsmPrinter::Impl::Impl(raw_ostream &os, AsmStateImpl &state)
|
|
|
|
: os(os), state(state), printerFlags(state.getPrinterFlags()) {}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printTrailingLocation(Location loc, bool allowAlias) {
|
2020-01-09 12:39:26 -08:00
|
|
|
// Check to see if we are printing debug information.
|
|
|
|
if (!printerFlags.shouldPrintDebugInfo())
|
|
|
|
return;
|
|
|
|
|
|
|
|
os << " ";
|
2021-05-23 14:08:31 -07:00
|
|
|
printLocation(loc, /*allowAlias=*/allowAlias);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
2022-11-28 18:35:00 -08:00
|
|
|
void AsmPrinter::Impl::printLocationInternal(LocationAttr loc, bool pretty,
|
|
|
|
bool isTopLevel) {
|
|
|
|
// If this isn't a top-level location, check for an alias.
|
|
|
|
if (!isTopLevel && succeeded(state.getAliasState().getAlias(loc, os)))
|
|
|
|
return;
|
|
|
|
|
2020-08-07 13:30:29 -07:00
|
|
|
TypeSwitch<LocationAttr>(loc)
|
|
|
|
.Case<OpaqueLoc>([&](OpaqueLoc loc) {
|
|
|
|
printLocationInternal(loc.getFallbackLocation(), pretty);
|
|
|
|
})
|
|
|
|
.Case<UnknownLoc>([&](UnknownLoc loc) {
|
|
|
|
if (pretty)
|
|
|
|
os << "[unknown]";
|
|
|
|
else
|
|
|
|
os << "unknown";
|
|
|
|
})
|
2024-11-23 08:12:04 -05:00
|
|
|
.Case<FileLineColRange>([&](FileLineColRange loc) {
|
2022-05-24 01:55:27 -07:00
|
|
|
if (pretty)
|
2021-11-11 01:44:58 +00:00
|
|
|
os << loc.getFilename().getValue();
|
2022-05-24 01:55:27 -07:00
|
|
|
else
|
|
|
|
printEscapedString(loc.getFilename());
|
2024-11-23 08:12:04 -05:00
|
|
|
if (loc.getEndColumn() == loc.getStartColumn() &&
|
|
|
|
loc.getStartLine() == loc.getEndLine()) {
|
|
|
|
os << ':' << loc.getStartLine() << ':' << loc.getStartColumn();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (loc.getStartLine() == loc.getEndLine()) {
|
|
|
|
os << ':' << loc.getStartLine() << ':' << loc.getStartColumn()
|
|
|
|
<< " to :" << loc.getEndColumn();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
os << ':' << loc.getStartLine() << ':' << loc.getStartColumn() << " to "
|
|
|
|
<< loc.getEndLine() << ':' << loc.getEndColumn();
|
2020-08-07 13:30:29 -07:00
|
|
|
})
|
|
|
|
.Case<NameLoc>([&](NameLoc loc) {
|
2022-05-24 01:55:27 -07:00
|
|
|
printEscapedString(loc.getName());
|
2020-08-07 13:30:29 -07:00
|
|
|
|
|
|
|
// Print the child if it isn't unknown.
|
|
|
|
auto childLoc = loc.getChildLoc();
|
2023-05-11 11:10:46 +02:00
|
|
|
if (!llvm::isa<UnknownLoc>(childLoc)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
os << '(';
|
|
|
|
printLocationInternal(childLoc, pretty);
|
|
|
|
os << ')';
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.Case<CallSiteLoc>([&](CallSiteLoc loc) {
|
|
|
|
Location caller = loc.getCaller();
|
|
|
|
Location callee = loc.getCallee();
|
|
|
|
if (!pretty)
|
|
|
|
os << "callsite(";
|
|
|
|
printLocationInternal(callee, pretty);
|
|
|
|
if (pretty) {
|
2023-05-11 11:10:46 +02:00
|
|
|
if (llvm::isa<NameLoc>(callee)) {
|
|
|
|
if (llvm::isa<FileLineColLoc>(caller)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
os << " at ";
|
|
|
|
} else {
|
|
|
|
os << newLine << " at ";
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
os << newLine << " at ";
|
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
} else {
|
2020-08-07 13:30:29 -07:00
|
|
|
os << " at ";
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
2020-08-07 13:30:29 -07:00
|
|
|
printLocationInternal(caller, pretty);
|
|
|
|
if (!pretty)
|
|
|
|
os << ")";
|
|
|
|
})
|
|
|
|
.Case<FusedLoc>([&](FusedLoc loc) {
|
|
|
|
if (!pretty)
|
|
|
|
os << "fused";
|
2022-10-22 14:01:41 -07:00
|
|
|
if (Attribute metadata = loc.getMetadata()) {
|
|
|
|
os << '<';
|
|
|
|
printAttribute(metadata);
|
|
|
|
os << '>';
|
|
|
|
}
|
2020-08-07 13:30:29 -07:00
|
|
|
os << '[';
|
|
|
|
interleave(
|
|
|
|
loc.getLocations(),
|
|
|
|
[&](Location loc) { printLocationInternal(loc, pretty); },
|
|
|
|
[&]() { os << ", "; });
|
|
|
|
os << ']';
|
2024-10-03 10:25:44 -07:00
|
|
|
})
|
|
|
|
.Default([&](LocationAttr loc) {
|
|
|
|
// Assumes that this is a dialect-specific attribute and prints it
|
|
|
|
// directly.
|
|
|
|
printAttribute(loc);
|
2020-08-07 13:30:29 -07:00
|
|
|
});
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Print a floating point value in a way that the parser will be able to
|
|
|
|
/// round-trip losslessly.
|
2024-06-06 07:51:47 -07:00
|
|
|
static void printFloatValue(const APFloat &apValue, raw_ostream &os,
|
|
|
|
bool *printedHex = nullptr) {
|
2020-01-09 12:39:26 -08:00
|
|
|
// We would like to output the FP constant value in exponential notation,
|
|
|
|
// but we cannot do this if doing so will lose precision. Check here to
|
|
|
|
// make sure that we only output it in exponential format if we can parse
|
|
|
|
// the value back and get the same value.
|
|
|
|
bool isInf = apValue.isInfinity();
|
|
|
|
bool isNaN = apValue.isNaN();
|
|
|
|
if (!isInf && !isNaN) {
|
|
|
|
SmallString<128> strValue;
|
2020-02-06 18:05:32 -08:00
|
|
|
apValue.toString(strValue, /*FormatPrecision=*/6, /*FormatMaxPadding=*/0,
|
|
|
|
/*TruncateZero=*/false);
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
// Check to make sure that the stringized number is not some string like
|
|
|
|
// "Inf" or NaN, that atof will accept, but the lexer will not. Check
|
|
|
|
// that the string matches the "[-+]?[0-9]" regex.
|
|
|
|
assert(((strValue[0] >= '0' && strValue[0] <= '9') ||
|
|
|
|
((strValue[0] == '-' || strValue[0] == '+') &&
|
|
|
|
(strValue[1] >= '0' && strValue[1] <= '9'))) &&
|
|
|
|
"[-+]?[0-9] regex does not match!");
|
|
|
|
|
|
|
|
// Parse back the stringized version and check that the value is equal
|
2020-02-06 18:05:32 -08:00
|
|
|
// (i.e., there is no precision loss).
|
|
|
|
if (APFloat(apValue.getSemantics(), strValue).bitwiseIsEqual(apValue)) {
|
|
|
|
os << strValue;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If it is not, use the default format of APFloat instead of the
|
|
|
|
// exponential notation.
|
|
|
|
strValue.clear();
|
|
|
|
apValue.toString(strValue);
|
|
|
|
|
|
|
|
// Make sure that we can parse the default form as a float.
|
2021-07-08 13:30:14 -07:00
|
|
|
if (strValue.str().contains('.')) {
|
2020-02-06 18:05:32 -08:00
|
|
|
os << strValue;
|
|
|
|
return;
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-06 18:05:32 -08:00
|
|
|
// Print special values in hexadecimal format. The sign bit should be included
|
|
|
|
// in the literal.
|
2024-06-06 07:51:47 -07:00
|
|
|
if (printedHex)
|
|
|
|
*printedHex = true;
|
2020-01-09 12:39:26 -08:00
|
|
|
SmallVector<char, 16> str;
|
|
|
|
APInt apInt = apValue.bitcastToAPInt();
|
|
|
|
apInt.toString(str, /*Radix=*/16, /*Signed=*/false,
|
|
|
|
/*formatAsCLiteral=*/true);
|
|
|
|
os << str;
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printLocation(LocationAttr loc, bool allowAlias) {
|
2020-11-09 21:50:47 -08:00
|
|
|
if (printerFlags.shouldPrintDebugInfoPrettyForm())
|
2022-11-28 18:35:00 -08:00
|
|
|
return printLocationInternal(loc, /*pretty=*/true, /*isTopLevel=*/true);
|
2020-11-09 21:50:47 -08:00
|
|
|
|
|
|
|
os << "loc(";
|
2022-09-02 21:23:47 -07:00
|
|
|
if (!allowAlias || failed(printAlias(loc)))
|
2022-11-28 18:35:00 -08:00
|
|
|
printLocationInternal(loc, /*pretty=*/false, /*isTopLevel=*/true);
|
2020-11-09 21:50:47 -08:00
|
|
|
os << ')';
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
2020-08-30 13:29:53 +05:30
|
|
|
/// Returns true if the given dialect symbol data is simple enough to print in
|
2022-07-05 16:20:30 -07:00
|
|
|
/// the pretty form. This is essentially when the symbol takes the form:
|
|
|
|
/// identifier (`<` body `>`)?
|
2020-01-09 12:39:26 -08:00
|
|
|
static bool isDialectSymbolSimpleEnoughForPrettyForm(StringRef symName) {
|
|
|
|
// The name must start with an identifier.
|
|
|
|
if (symName.empty() || !isalpha(symName.front()))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Ignore all the characters that are valid in an identifier in the symbol
|
|
|
|
// name.
|
|
|
|
symName = symName.drop_while(
|
|
|
|
[](char c) { return llvm::isAlnum(c) || c == '.' || c == '_'; });
|
|
|
|
if (symName.empty())
|
|
|
|
return true;
|
|
|
|
|
2022-07-05 16:20:30 -07:00
|
|
|
// If we got to an unexpected character, then it must be a <>. Check that the
|
|
|
|
// rest of the symbol is wrapped within <>.
|
|
|
|
return symName.front() == '<' && symName.back() == '>';
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Print the given dialect symbol to the stream.
|
|
|
|
static void printDialectSymbol(raw_ostream &os, StringRef symPrefix,
|
|
|
|
StringRef dialectName, StringRef symString) {
|
|
|
|
os << symPrefix << dialectName;
|
|
|
|
|
|
|
|
// If this symbol name is simple enough, print it directly in pretty form,
|
|
|
|
// otherwise, we print it as an escaped string.
|
|
|
|
if (isDialectSymbolSimpleEnoughForPrettyForm(symString)) {
|
|
|
|
os << '.' << symString;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-07-05 16:20:30 -07:00
|
|
|
os << '<' << symString << '>';
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
2020-08-30 13:29:53 +05:30
|
|
|
/// Returns true if the given string can be represented as a bare identifier.
|
2020-01-09 12:39:26 -08:00
|
|
|
static bool isBareIdentifier(StringRef name) {
|
|
|
|
// By making this unsigned, the value passed in to isalnum will always be
|
|
|
|
// in the range 0-255. This is important when building with MSVC because
|
|
|
|
// its implementation will assert. This situation can arise when dealing
|
|
|
|
// with UTF-8 multibyte characters.
|
2021-10-12 13:29:29 -07:00
|
|
|
if (name.empty() || (!isalpha(name[0]) && name[0] != '_'))
|
2020-01-09 12:39:26 -08:00
|
|
|
return false;
|
|
|
|
return llvm::all_of(name.drop_front(), [](unsigned char c) {
|
|
|
|
return isalnum(c) || c == '_' || c == '$' || c == '.';
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-10-12 13:29:29 -07:00
|
|
|
/// Print the given string as a keyword, or a quoted and escaped string if it
|
|
|
|
/// has any special or non-printable characters in it.
|
|
|
|
static void printKeywordOrString(StringRef keyword, raw_ostream &os) {
|
|
|
|
// If it can be represented as a bare identifier, write it directly.
|
|
|
|
if (isBareIdentifier(keyword)) {
|
|
|
|
os << keyword;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, output the keyword wrapped in quotes with proper escaping.
|
|
|
|
os << "\"";
|
|
|
|
printEscapedString(keyword, os);
|
|
|
|
os << '"';
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the given string as a symbol reference. A symbol reference is
|
|
|
|
/// represented as a string prefixed with '@'. The reference is surrounded with
|
|
|
|
/// ""'s and escaped if it has any special or non-printable characters in it.
|
|
|
|
static void printSymbolReference(StringRef symbolRef, raw_ostream &os) {
|
2023-01-30 12:48:07 -08:00
|
|
|
if (symbolRef.empty()) {
|
|
|
|
os << "@<<INVALID EMPTY SYMBOL>>";
|
|
|
|
return;
|
|
|
|
}
|
2021-10-12 13:29:29 -07:00
|
|
|
os << '@';
|
|
|
|
printKeywordOrString(symbolRef, os);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Print out a valid ElementsAttr that is succinct and can represent any
|
|
|
|
// potential shape/type, for use when eliding a large ElementsAttr.
|
|
|
|
//
|
2022-07-15 20:08:32 -07:00
|
|
|
// We choose to use a dense resource ElementsAttr literal with conspicuous
|
|
|
|
// content to hopefully alert readers to the fact that this has been elided.
|
2020-01-09 12:39:26 -08:00
|
|
|
static void printElidedElementsAttr(raw_ostream &os) {
|
2022-07-15 20:08:32 -07:00
|
|
|
os << R"(dense_resource<__elided__>)";
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
2025-02-04 12:49:15 -08:00
|
|
|
void AsmPrinter::Impl::printResourceHandle(
|
|
|
|
const AsmDialectResourceHandle &resource) {
|
|
|
|
auto *interface = cast<OpAsmDialectInterface>(resource.getDialect());
|
|
|
|
::printKeywordOrString(interface->getResourceKey(resource), os);
|
|
|
|
state.getDialectResources()[resource.getDialect()].insert(resource);
|
|
|
|
}
|
|
|
|
|
2021-12-08 01:24:51 +00:00
|
|
|
LogicalResult AsmPrinter::Impl::printAlias(Attribute attr) {
|
2022-09-02 21:23:47 -07:00
|
|
|
return state.getAliasState().getAlias(attr, os);
|
2021-12-08 01:24:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult AsmPrinter::Impl::printAlias(Type type) {
|
2022-09-02 21:23:47 -07:00
|
|
|
return state.getAliasState().getAlias(type, os);
|
2021-12-08 01:24:51 +00:00
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printAttribute(Attribute attr,
|
|
|
|
AttrTypeElision typeElision) {
|
2020-01-09 12:39:26 -08:00
|
|
|
if (!attr) {
|
|
|
|
os << "<<NULL ATTRIBUTE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// Try to print an alias for this attribute.
|
2021-12-08 01:24:51 +00:00
|
|
|
if (succeeded(printAlias(attr)))
|
2020-10-30 00:30:59 -07:00
|
|
|
return;
|
2022-10-22 14:01:41 -07:00
|
|
|
return printAttributeImpl(attr, typeElision);
|
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
void AsmPrinter::Impl::printAttributeImpl(Attribute attr,
|
|
|
|
AttrTypeElision typeElision) {
|
2022-05-16 20:21:39 +00:00
|
|
|
if (!isa<BuiltinDialect>(attr.getDialect())) {
|
|
|
|
printDialectAttribute(attr);
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto opaqueAttr = llvm::dyn_cast<OpaqueAttr>(attr)) {
|
2020-01-09 12:39:26 -08:00
|
|
|
printDialectSymbol(os, "#", opaqueAttr.getDialectNamespace(),
|
|
|
|
opaqueAttr.getAttrData());
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (llvm::isa<UnitAttr>(attr)) {
|
2020-01-09 12:39:26 -08:00
|
|
|
os << "unit";
|
2020-08-07 13:30:29 -07:00
|
|
|
return;
|
2023-07-11 07:30:18 +00:00
|
|
|
} else if (auto distinctAttr = llvm::dyn_cast<DistinctAttr>(attr)) {
|
|
|
|
os << "distinct[" << state.getDistinctState().getId(distinctAttr) << "]<";
|
2023-07-13 10:39:08 +02:00
|
|
|
if (!llvm::isa<UnitAttr>(distinctAttr.getReferencedAttr())) {
|
|
|
|
printAttribute(distinctAttr.getReferencedAttr());
|
|
|
|
}
|
2023-07-11 07:30:18 +00:00
|
|
|
os << '>';
|
|
|
|
return;
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto dictAttr = llvm::dyn_cast<DictionaryAttr>(attr)) {
|
2020-01-09 12:39:26 -08:00
|
|
|
os << '{';
|
2020-08-07 13:30:29 -07:00
|
|
|
interleaveComma(dictAttr.getValue(),
|
2020-03-11 13:22:19 -07:00
|
|
|
[&](NamedAttribute attr) { printNamedAttribute(attr); });
|
2020-01-09 12:39:26 -08:00
|
|
|
os << '}';
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto intAttr = llvm::dyn_cast<IntegerAttr>(attr)) {
|
[mlir] Remove types from attributes
This patch removes the `type` field from `Attribute` along with the
`Attribute::getType` accessor.
Going forward, this means that attributes in MLIR will no longer have
types as a first-class concept. This patch lays the groundwork to
incrementally remove or refactor code that relies on generic attributes
being typed. The immediate impact will be on attributes that rely on
`Attribute` containing a type, such as `IntegerAttr`,
`DenseElementsAttr`, and `ml_program::ExternAttr`, which will now need
to define a type parameter on their storage classes. This will save
memory as all other attribute kinds will no longer contain a type.
Moreover, it will not be possible to generically query the type of an
attribute directly. This patch provides an attribute interface
`TypedAttr` that implements only one method, `getType`, which can be
used to generically query the types of attributes that implement the
interface. This interface can be used to retain the concept of a "typed
attribute". The ODS-generated accessor for a `type` parameter
automatically implements this method.
Next steps will be to refactor the assembly formats of certain operations
that rely on `parseAttribute(type)` and `printAttributeWithoutType` to
remove special handling of type elision until `type` can be removed from
the dialect parsing hook entirely; and incrementally remove uses of
`TypedAttr`.
Reviewed By: lattner, rriddle, jpienaar
Differential Revision: https://reviews.llvm.org/D130092
2022-07-18 21:32:38 -07:00
|
|
|
Type intType = intAttr.getType();
|
|
|
|
if (intType.isSignlessInteger(1)) {
|
2020-06-02 18:20:38 -07:00
|
|
|
os << (intAttr.getValue().getBoolValue() ? "true" : "false");
|
|
|
|
|
|
|
|
// Boolean integer attributes always elides the type.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
Allow single-bit integer types to have signs. A signed one bit integer is either 0 or -1.
Reviewers: rriddle!
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D77832
2020-04-09 14:58:28 -07:00
|
|
|
// Only print attributes as unsigned if they are explicitly unsigned or are
|
|
|
|
// signless 1-bit values. Indexes, signed values, and multi-bit signless
|
|
|
|
// values print as signed.
|
|
|
|
bool isUnsigned =
|
[mlir] Remove types from attributes
This patch removes the `type` field from `Attribute` along with the
`Attribute::getType` accessor.
Going forward, this means that attributes in MLIR will no longer have
types as a first-class concept. This patch lays the groundwork to
incrementally remove or refactor code that relies on generic attributes
being typed. The immediate impact will be on attributes that rely on
`Attribute` containing a type, such as `IntegerAttr`,
`DenseElementsAttr`, and `ml_program::ExternAttr`, which will now need
to define a type parameter on their storage classes. This will save
memory as all other attribute kinds will no longer contain a type.
Moreover, it will not be possible to generically query the type of an
attribute directly. This patch provides an attribute interface
`TypedAttr` that implements only one method, `getType`, which can be
used to generically query the types of attributes that implement the
interface. This interface can be used to retain the concept of a "typed
attribute". The ODS-generated accessor for a `type` parameter
automatically implements this method.
Next steps will be to refactor the assembly formats of certain operations
that rely on `parseAttribute(type)` and `printAttributeWithoutType` to
remove special handling of type elision until `type` can be removed from
the dialect parsing hook entirely; and incrementally remove uses of
`TypedAttr`.
Reviewed By: lattner, rriddle, jpienaar
Differential Revision: https://reviews.llvm.org/D130092
2022-07-18 21:32:38 -07:00
|
|
|
intType.isUnsignedInteger() || intType.isSignlessInteger(1);
|
Allow single-bit integer types to have signs. A signed one bit integer is either 0 or -1.
Reviewers: rriddle!
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D77832
2020-04-09 14:58:28 -07:00
|
|
|
intAttr.getValue().print(os, !isUnsigned);
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
// IntegerAttr elides the type if I64.
|
[mlir] Remove types from attributes
This patch removes the `type` field from `Attribute` along with the
`Attribute::getType` accessor.
Going forward, this means that attributes in MLIR will no longer have
types as a first-class concept. This patch lays the groundwork to
incrementally remove or refactor code that relies on generic attributes
being typed. The immediate impact will be on attributes that rely on
`Attribute` containing a type, such as `IntegerAttr`,
`DenseElementsAttr`, and `ml_program::ExternAttr`, which will now need
to define a type parameter on their storage classes. This will save
memory as all other attribute kinds will no longer contain a type.
Moreover, it will not be possible to generically query the type of an
attribute directly. This patch provides an attribute interface
`TypedAttr` that implements only one method, `getType`, which can be
used to generically query the types of attributes that implement the
interface. This interface can be used to retain the concept of a "typed
attribute". The ODS-generated accessor for a `type` parameter
automatically implements this method.
Next steps will be to refactor the assembly formats of certain operations
that rely on `parseAttribute(type)` and `printAttributeWithoutType` to
remove special handling of type elision until `type` can be removed from
the dialect parsing hook entirely; and incrementally remove uses of
`TypedAttr`.
Reviewed By: lattner, rriddle, jpienaar
Differential Revision: https://reviews.llvm.org/D130092
2022-07-18 21:32:38 -07:00
|
|
|
if (typeElision == AttrTypeElision::May && intType.isSignlessInteger(64))
|
2020-01-09 12:39:26 -08:00
|
|
|
return;
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto floatAttr = llvm::dyn_cast<FloatAttr>(attr)) {
|
2024-06-06 07:51:47 -07:00
|
|
|
bool printedHex = false;
|
|
|
|
printFloatValue(floatAttr.getValue(), os, &printedHex);
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
// FloatAttr elides the type if F64.
|
2024-06-06 07:51:47 -07:00
|
|
|
if (typeElision == AttrTypeElision::May && floatAttr.getType().isF64() &&
|
|
|
|
!printedHex)
|
2020-01-09 12:39:26 -08:00
|
|
|
return;
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto strAttr = llvm::dyn_cast<StringAttr>(attr)) {
|
2022-05-24 01:55:27 -07:00
|
|
|
printEscapedString(strAttr.getValue());
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto arrayAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
|
2018-07-18 16:29:21 -07:00
|
|
|
os << '[';
|
2020-08-07 13:30:29 -07:00
|
|
|
interleaveComma(arrayAttr.getValue(), [&](Attribute attr) {
|
2020-02-08 10:01:17 -08:00
|
|
|
printAttribute(attr, AttrTypeElision::May);
|
2019-06-26 18:29:25 -07:00
|
|
|
});
|
2018-07-18 16:29:21 -07:00
|
|
|
os << ']';
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto affineMapAttr = llvm::dyn_cast<AffineMapAttr>(attr)) {
|
2020-01-13 13:12:37 -08:00
|
|
|
os << "affine_map<";
|
2020-08-07 13:30:29 -07:00
|
|
|
affineMapAttr.getValue().print(os);
|
2020-01-13 13:12:37 -08:00
|
|
|
os << '>';
|
2019-06-26 18:29:25 -07:00
|
|
|
|
|
|
|
// AffineMap always elides the type.
|
|
|
|
return;
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto integerSetAttr = llvm::dyn_cast<IntegerSetAttr>(attr)) {
|
2020-01-13 13:12:37 -08:00
|
|
|
os << "affine_set<";
|
2020-08-07 13:30:29 -07:00
|
|
|
integerSetAttr.getValue().print(os);
|
2020-01-13 13:12:37 -08:00
|
|
|
os << '>';
|
|
|
|
|
|
|
|
// IntegerSet always elides the type.
|
|
|
|
return;
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
printType(typeAttr.getValue());
|
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto refAttr = llvm::dyn_cast<SymbolRefAttr>(attr)) {
|
2021-08-29 14:22:24 -07:00
|
|
|
printSymbolReference(refAttr.getRootReference().getValue(), os);
|
2019-11-11 18:18:02 -08:00
|
|
|
for (FlatSymbolRefAttr nestedRef : refAttr.getNestedReferences()) {
|
|
|
|
os << "::";
|
|
|
|
printSymbolReference(nestedRef.getValue(), os);
|
|
|
|
}
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto intOrFpEltAttr =
|
|
|
|
llvm::dyn_cast<DenseIntOrFPElementsAttr>(attr)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
if (printerFlags.shouldElideElementsAttr(intOrFpEltAttr)) {
|
2019-12-04 10:19:20 -08:00
|
|
|
printElidedElementsAttr(os);
|
2020-08-07 13:30:29 -07:00
|
|
|
} else {
|
|
|
|
os << "dense<";
|
|
|
|
printDenseIntOrFPElementsAttr(intOrFpEltAttr, /*allowHex=*/true);
|
|
|
|
os << '>';
|
2019-12-04 10:19:20 -08:00
|
|
|
}
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto strEltAttr = llvm::dyn_cast<DenseStringElementsAttr>(attr)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
if (printerFlags.shouldElideElementsAttr(strEltAttr)) {
|
2020-04-23 19:01:51 -07:00
|
|
|
printElidedElementsAttr(os);
|
2020-08-07 13:30:29 -07:00
|
|
|
} else {
|
|
|
|
os << "dense<";
|
|
|
|
printDenseStringElementsAttr(strEltAttr);
|
|
|
|
os << '>';
|
2020-04-23 19:01:51 -07:00
|
|
|
}
|
2020-08-07 13:30:29 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto sparseEltAttr = llvm::dyn_cast<SparseElementsAttr>(attr)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
if (printerFlags.shouldElideElementsAttr(sparseEltAttr.getIndices()) ||
|
|
|
|
printerFlags.shouldElideElementsAttr(sparseEltAttr.getValues())) {
|
2019-12-04 10:19:20 -08:00
|
|
|
printElidedElementsAttr(os);
|
2020-08-07 13:30:29 -07:00
|
|
|
} else {
|
|
|
|
os << "sparse<";
|
|
|
|
DenseIntElementsAttr indices = sparseEltAttr.getIndices();
|
|
|
|
if (indices.getNumElements() != 0) {
|
|
|
|
printDenseIntOrFPElementsAttr(indices, /*allowHex=*/false);
|
|
|
|
os << ", ";
|
|
|
|
printDenseElementsAttr(sparseEltAttr.getValues(), /*allowHex=*/true);
|
|
|
|
}
|
|
|
|
os << '>';
|
2020-07-08 17:44:27 -07:00
|
|
|
}
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto stridedLayoutAttr = llvm::dyn_cast<StridedLayoutAttr>(attr)) {
|
[mlir] materialize strided memref layout as attribute
Introduce a new attribute to represent the strided memref layout. Strided
layouts are omnipresent in code generation flows and are the only kind of
layouts produced and supported by a half of operation in the memref dialect
(view-related, shape-related). However, they are internally represented as
affine maps that require a somewhat fragile extraction of the strides from the
linear form that also comes with an overhead. Furthermore, textual
representation of strided layouts as affine maps is difficult to read: compare
`affine_map<(d0, d1, d2)[s0, s1] -> (d0*32 + d1*s0 + s1 + d2)>` with
`strides: [32, ?, 1], offset: ?`. While a rudimentary support for parsing a
syntactically sugared version of the strided layout has existed in the codebase
for a long time, it does not go as far as this commit to make the strided
layout a first-class attribute in the IR.
This introduces the attribute and updates the tests that using the pre-existing
sugared form to use the new attribute instead. Most memref created
programmatically, e.g., in passes, still use the affine form with further
extraction of strides and will be updated separately.
Update and clean-up the memref type documentation that has gotten stale and has
been referring to the details of affine map composition that are long gone.
See https://discourse.llvm.org/t/rfc-materialize-strided-memref-layout-as-an-attribute/64211.
Reviewed By: nicolasvasilache
Differential Revision: https://reviews.llvm.org/D132864
2022-08-30 10:23:57 +02:00
|
|
|
stridedLayoutAttr.print(os);
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto denseArrayAttr = llvm::dyn_cast<DenseArrayAttr>(attr)) {
|
2022-08-30 12:13:15 -07:00
|
|
|
os << "array<";
|
2022-11-07 20:20:59 -08:00
|
|
|
printType(denseArrayAttr.getElementType());
|
2022-08-25 16:21:28 -07:00
|
|
|
if (!denseArrayAttr.empty()) {
|
2022-11-07 20:20:59 -08:00
|
|
|
os << ": ";
|
2022-08-25 16:21:28 -07:00
|
|
|
printDenseArrayAttr(denseArrayAttr);
|
|
|
|
}
|
2022-08-11 19:05:48 -04:00
|
|
|
os << ">";
|
2022-08-30 12:13:15 -07:00
|
|
|
return;
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto resourceAttr =
|
|
|
|
llvm::dyn_cast<DenseResourceElementsAttr>(attr)) {
|
[mlir] Add a new builtin DenseResourceElementsAttr
This attributes is intended cover the current set of use cases that abuse
DenseElementsAttr, e.g. when the data is large. Using resources for large
data is one of the major reasons why they were added; e.g. they can be
deallocated mid-compilation, they support a wide variety of data origins
(e.g, heap allocated, mmap'd, etc.), they can support mutation, etc.
I considered at length not having a builtin variant of this, and instead
having multiple versions of this attribute for dialects that are interested,
but they all boiled down to the exact same attribute definition. Given the
generality of this attribute, it feels more aligned to keep it next to DenseArrayAttr
(given that DenseArrayAttr covers the "small" case, and DenseResourcesElementsAttr
covers the "large" case). The underlying infra used to build this attribute is
general, and having a builtin attribute doesn't preclude users from defining
their own when it makes sense (they can even share a blob manager with the
builtin dialect to avoid data duplication).
Differential Revision: https://reviews.llvm.org/D130022
2022-07-19 18:22:55 -07:00
|
|
|
os << "dense_resource<";
|
|
|
|
printResourceHandle(resourceAttr.getRawHandle());
|
|
|
|
os << ">";
|
2023-05-11 11:10:46 +02:00
|
|
|
} else if (auto locAttr = llvm::dyn_cast<LocationAttr>(attr)) {
|
2020-08-07 13:30:29 -07:00
|
|
|
printLocation(locAttr);
|
Introduce a new Dense Array attribute
This attribute is similar to DenseElementsAttr but does not support
splat. As such it has a much simpler API and does not need any smart
iterator: it exposes direct ArrayRef access.
A new syntax is introduced so that the generic printing/parsing looks
like:
[:i64 1, -2, 3]
This attribute beings like an ArrayAttr but has a `:` token after the
opening square brace to introduce the element type (supported are I8,
I16, I32, I64, F32, F64) and the comma separated list for the data.
This is particularly convenient for attributes intended to be small,
like those referring to shapes.
For example a `transpose` operation with a `dims` attribute could be
defined as such:
let arguments = (ins AnyTensor:$input, DenseI64ArrayAttr:$dims);
let assemblyFormat = "$input `dims` `=` $dims attr-dict : type($input)";
And printed this way (the element type is elided in this case):
transpose %input dims = [0, 2, 1] : tensor<2x3x4xf32>
The C++ API for dims would just directly return an ArrayRef<int64>
RFC: https://discourse.llvm.org/t/rfc-introduce-a-new-dense-array-attribute/63279
Recommit with a custom DenseArrayBaseAttrStorage class to ensure
over-alignment of the storage to the largest type.
Reviewed By: rriddle
Differential Revision: https://reviews.llvm.org/D123774
2022-06-28 11:29:27 +00:00
|
|
|
} else {
|
|
|
|
llvm::report_fatal_error("Unknown builtin attribute");
|
2018-07-18 16:29:21 -07:00
|
|
|
}
|
2020-02-08 10:01:17 -08:00
|
|
|
// Don't print the type if we must elide it, or if it is a None type.
|
[mlir] Remove types from attributes
This patch removes the `type` field from `Attribute` along with the
`Attribute::getType` accessor.
Going forward, this means that attributes in MLIR will no longer have
types as a first-class concept. This patch lays the groundwork to
incrementally remove or refactor code that relies on generic attributes
being typed. The immediate impact will be on attributes that rely on
`Attribute` containing a type, such as `IntegerAttr`,
`DenseElementsAttr`, and `ml_program::ExternAttr`, which will now need
to define a type parameter on their storage classes. This will save
memory as all other attribute kinds will no longer contain a type.
Moreover, it will not be possible to generically query the type of an
attribute directly. This patch provides an attribute interface
`TypedAttr` that implements only one method, `getType`, which can be
used to generically query the types of attributes that implement the
interface. This interface can be used to retain the concept of a "typed
attribute". The ODS-generated accessor for a `type` parameter
automatically implements this method.
Next steps will be to refactor the assembly formats of certain operations
that rely on `parseAttribute(type)` and `printAttributeWithoutType` to
remove special handling of type elision until `type` can be removed from
the dialect parsing hook entirely; and incrementally remove uses of
`TypedAttr`.
Reviewed By: lattner, rriddle, jpienaar
Differential Revision: https://reviews.llvm.org/D130092
2022-07-18 21:32:38 -07:00
|
|
|
if (typeElision != AttrTypeElision::Must) {
|
2023-05-11 11:10:46 +02:00
|
|
|
if (auto typedAttr = llvm::dyn_cast<TypedAttr>(attr)) {
|
[mlir] Remove types from attributes
This patch removes the `type` field from `Attribute` along with the
`Attribute::getType` accessor.
Going forward, this means that attributes in MLIR will no longer have
types as a first-class concept. This patch lays the groundwork to
incrementally remove or refactor code that relies on generic attributes
being typed. The immediate impact will be on attributes that rely on
`Attribute` containing a type, such as `IntegerAttr`,
`DenseElementsAttr`, and `ml_program::ExternAttr`, which will now need
to define a type parameter on their storage classes. This will save
memory as all other attribute kinds will no longer contain a type.
Moreover, it will not be possible to generically query the type of an
attribute directly. This patch provides an attribute interface
`TypedAttr` that implements only one method, `getType`, which can be
used to generically query the types of attributes that implement the
interface. This interface can be used to retain the concept of a "typed
attribute". The ODS-generated accessor for a `type` parameter
automatically implements this method.
Next steps will be to refactor the assembly formats of certain operations
that rely on `parseAttribute(type)` and `printAttributeWithoutType` to
remove special handling of type elision until `type` can be removed from
the dialect parsing hook entirely; and incrementally remove uses of
`TypedAttr`.
Reviewed By: lattner, rriddle, jpienaar
Differential Revision: https://reviews.llvm.org/D130092
2022-07-18 21:32:38 -07:00
|
|
|
Type attrType = typedAttr.getType();
|
2023-05-11 11:10:46 +02:00
|
|
|
if (!llvm::isa<NoneType>(attrType)) {
|
[mlir] Remove types from attributes
This patch removes the `type` field from `Attribute` along with the
`Attribute::getType` accessor.
Going forward, this means that attributes in MLIR will no longer have
types as a first-class concept. This patch lays the groundwork to
incrementally remove or refactor code that relies on generic attributes
being typed. The immediate impact will be on attributes that rely on
`Attribute` containing a type, such as `IntegerAttr`,
`DenseElementsAttr`, and `ml_program::ExternAttr`, which will now need
to define a type parameter on their storage classes. This will save
memory as all other attribute kinds will no longer contain a type.
Moreover, it will not be possible to generically query the type of an
attribute directly. This patch provides an attribute interface
`TypedAttr` that implements only one method, `getType`, which can be
used to generically query the types of attributes that implement the
interface. This interface can be used to retain the concept of a "typed
attribute". The ODS-generated accessor for a `type` parameter
automatically implements this method.
Next steps will be to refactor the assembly formats of certain operations
that rely on `parseAttribute(type)` and `printAttributeWithoutType` to
remove special handling of type elision until `type` can be removed from
the dialect parsing hook entirely; and incrementally remove uses of
`TypedAttr`.
Reviewed By: lattner, rriddle, jpienaar
Differential Revision: https://reviews.llvm.org/D130092
2022-07-18 21:32:38 -07:00
|
|
|
os << " : ";
|
|
|
|
printType(attrType);
|
|
|
|
}
|
|
|
|
}
|
2019-06-26 18:29:25 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-05 12:39:22 -07:00
|
|
|
/// Print the integer element of a DenseElementsAttr.
|
|
|
|
static void printDenseIntElement(const APInt &value, raw_ostream &os,
|
2022-08-25 16:21:28 -07:00
|
|
|
Type type) {
|
|
|
|
if (type.isInteger(1))
|
2019-07-18 09:24:41 -07:00
|
|
|
os << (value.getBoolValue() ? "true" : "false");
|
|
|
|
else
|
2022-08-25 16:21:28 -07:00
|
|
|
value.print(os, !type.isUnsignedInteger());
|
2019-06-26 18:29:25 -07:00
|
|
|
}
|
|
|
|
|
2020-05-05 12:39:12 -07:00
|
|
|
static void
|
|
|
|
printDenseElementsAttrImpl(bool isSplat, ShapedType type, raw_ostream &os,
|
|
|
|
function_ref<void(unsigned)> printEltFn) {
|
2019-06-12 15:05:45 -07:00
|
|
|
// Special case for 0-d and splat tensors.
|
2020-05-05 12:39:12 -07:00
|
|
|
if (isSplat)
|
|
|
|
return printEltFn(0);
|
2019-04-01 10:01:47 -07:00
|
|
|
|
2018-10-18 13:54:44 -07:00
|
|
|
// Special case for degenerate tensors.
|
2019-06-26 18:29:25 -07:00
|
|
|
auto numElements = type.getNumElements();
|
2020-07-08 17:44:27 -07:00
|
|
|
if (numElements == 0)
|
2018-10-18 13:54:44 -07:00
|
|
|
return;
|
|
|
|
|
|
|
|
// We use a mixed-radix counter to iterate through the shape. When we bump a
|
|
|
|
// non-least-significant digit, we emit a close bracket. When we next emit an
|
|
|
|
// element we re-open all closed brackets.
|
|
|
|
|
|
|
|
// The mixed-radix counter, with radices in 'shape'.
|
2020-07-08 17:44:27 -07:00
|
|
|
int64_t rank = type.getRank();
|
2018-10-18 13:54:44 -07:00
|
|
|
SmallVector<unsigned, 4> counter(rank, 0);
|
|
|
|
// The number of brackets that have been opened and not closed.
|
|
|
|
unsigned openBrackets = 0;
|
|
|
|
|
2020-05-05 12:39:12 -07:00
|
|
|
auto shape = type.getShape();
|
|
|
|
auto bumpCounter = [&] {
|
2018-10-18 13:54:44 -07:00
|
|
|
// Bump the least significant digit.
|
|
|
|
++counter[rank - 1];
|
|
|
|
// Iterate backwards bubbling back the increment.
|
|
|
|
for (unsigned i = rank - 1; i > 0; --i)
|
|
|
|
if (counter[i] >= shape[i]) {
|
|
|
|
// Index 'i' is rolled over. Bump (i-1) and close a bracket.
|
|
|
|
counter[i] = 0;
|
|
|
|
++counter[i - 1];
|
|
|
|
--openBrackets;
|
|
|
|
os << ']';
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-06-26 18:29:25 -07:00
|
|
|
for (unsigned idx = 0, e = numElements; idx != e; ++idx) {
|
2018-10-18 13:54:44 -07:00
|
|
|
if (idx != 0)
|
|
|
|
os << ", ";
|
|
|
|
while (openBrackets++ < rank)
|
|
|
|
os << '[';
|
|
|
|
openBrackets = rank;
|
2020-05-05 12:39:12 -07:00
|
|
|
printEltFn(idx);
|
2018-10-18 13:54:44 -07:00
|
|
|
bumpCounter();
|
|
|
|
}
|
|
|
|
while (openBrackets-- > 0)
|
|
|
|
os << ']';
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printDenseElementsAttr(DenseElementsAttr attr,
|
|
|
|
bool allowHex) {
|
2023-05-11 11:10:46 +02:00
|
|
|
if (auto stringAttr = llvm::dyn_cast<DenseStringElementsAttr>(attr))
|
2020-05-05 12:39:12 -07:00
|
|
|
return printDenseStringElementsAttr(stringAttr);
|
2020-04-23 19:01:51 -07:00
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
printDenseIntOrFPElementsAttr(llvm::cast<DenseIntOrFPElementsAttr>(attr),
|
2020-05-05 12:39:12 -07:00
|
|
|
allowHex);
|
|
|
|
}
|
2020-04-23 19:01:51 -07:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printDenseIntOrFPElementsAttr(
|
|
|
|
DenseIntOrFPElementsAttr attr, bool allowHex) {
|
2020-05-05 12:39:12 -07:00
|
|
|
auto type = attr.getType();
|
|
|
|
auto elementType = type.getElementType();
|
|
|
|
|
|
|
|
// Check to see if we should format this attribute as a hex string.
|
2024-04-09 03:08:32 +03:00
|
|
|
if (allowHex && printerFlags.shouldPrintElementsAttrWithHex(attr)) {
|
2020-05-05 12:39:12 -07:00
|
|
|
ArrayRef<char> rawData = attr.getRawData();
|
2023-10-05 09:17:09 -07:00
|
|
|
if (llvm::endianness::native == llvm::endianness::big) {
|
2020-10-28 17:05:32 -07:00
|
|
|
// Convert endianess in big-endian(BE) machines. `rawData` is BE in BE
|
|
|
|
// machines. It is converted here to print in LE format.
|
|
|
|
SmallVector<char, 64> outDataVec(rawData.size());
|
|
|
|
MutableArrayRef<char> convRawData(outDataVec);
|
|
|
|
DenseIntOrFPElementsAttr::convertEndianOfArrayRefForBEmachine(
|
|
|
|
rawData, convRawData, type);
|
2022-05-24 01:55:27 -07:00
|
|
|
printHexString(convRawData);
|
2020-10-28 17:05:32 -07:00
|
|
|
} else {
|
2022-05-24 01:55:27 -07:00
|
|
|
printHexString(rawData);
|
2020-10-28 17:05:32 -07:00
|
|
|
}
|
|
|
|
|
2020-04-23 19:01:51 -07:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-05-11 11:10:46 +02:00
|
|
|
if (ComplexType complexTy = llvm::dyn_cast<ComplexType>(elementType)) {
|
2020-06-16 15:26:25 +01:00
|
|
|
Type complexElementType = complexTy.getElementType();
|
|
|
|
// Note: The if and else below had a common lambda function which invoked
|
|
|
|
// printDenseElementsAttrImpl. This lambda was hitting a bug in gcc 9.1,9.2
|
|
|
|
// and hence was replaced.
|
2023-05-11 11:10:46 +02:00
|
|
|
if (llvm::isa<IntegerType>(complexElementType)) {
|
2021-09-21 01:40:22 +00:00
|
|
|
auto valueIt = attr.value_begin<std::complex<APInt>>();
|
2020-05-05 12:39:22 -07:00
|
|
|
printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
|
2021-09-21 01:40:22 +00:00
|
|
|
auto complexValue = *(valueIt + index);
|
2020-05-05 12:39:22 -07:00
|
|
|
os << "(";
|
2022-08-25 16:21:28 -07:00
|
|
|
printDenseIntElement(complexValue.real(), os, complexElementType);
|
2020-05-05 12:39:22 -07:00
|
|
|
os << ",";
|
2022-08-25 16:21:28 -07:00
|
|
|
printDenseIntElement(complexValue.imag(), os, complexElementType);
|
2020-05-05 12:39:22 -07:00
|
|
|
os << ")";
|
|
|
|
});
|
2020-06-16 15:26:25 +01:00
|
|
|
} else {
|
2021-09-21 01:40:22 +00:00
|
|
|
auto valueIt = attr.value_begin<std::complex<APFloat>>();
|
2020-06-16 15:26:25 +01:00
|
|
|
printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
|
2021-09-21 01:40:22 +00:00
|
|
|
auto complexValue = *(valueIt + index);
|
2020-06-16 15:26:25 +01:00
|
|
|
os << "(";
|
|
|
|
printFloatValue(complexValue.real(), os);
|
|
|
|
os << ",";
|
|
|
|
printFloatValue(complexValue.imag(), os);
|
|
|
|
os << ")";
|
|
|
|
});
|
|
|
|
}
|
2020-05-05 12:39:22 -07:00
|
|
|
} else if (elementType.isIntOrIndex()) {
|
2021-09-21 01:40:22 +00:00
|
|
|
auto valueIt = attr.value_begin<APInt>();
|
2020-05-05 12:39:12 -07:00
|
|
|
printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
|
2022-08-25 16:21:28 -07:00
|
|
|
printDenseIntElement(*(valueIt + index), os, elementType);
|
2020-05-05 12:39:12 -07:00
|
|
|
});
|
|
|
|
} else {
|
2023-05-11 11:10:46 +02:00
|
|
|
assert(llvm::isa<FloatType>(elementType) && "unexpected element type");
|
2021-09-21 01:40:22 +00:00
|
|
|
auto valueIt = attr.value_begin<APFloat>();
|
2020-05-05 12:39:12 -07:00
|
|
|
printDenseElementsAttrImpl(attr.isSplat(), type, os, [&](unsigned index) {
|
2021-09-21 01:40:22 +00:00
|
|
|
printFloatValue(*(valueIt + index), os);
|
2020-05-05 12:39:12 -07:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2020-04-23 19:01:51 -07:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printDenseStringElementsAttr(
|
|
|
|
DenseStringElementsAttr attr) {
|
2020-05-05 12:39:12 -07:00
|
|
|
ArrayRef<StringRef> data = attr.getRawStringData();
|
2022-05-24 01:55:27 -07:00
|
|
|
auto printFn = [&](unsigned index) { printEscapedString(data[index]); };
|
2020-05-05 12:39:12 -07:00
|
|
|
printDenseElementsAttrImpl(attr.isSplat(), attr.getType(), os, printFn);
|
2020-04-23 19:01:51 -07:00
|
|
|
}
|
|
|
|
|
2022-08-25 16:21:28 -07:00
|
|
|
void AsmPrinter::Impl::printDenseArrayAttr(DenseArrayAttr attr) {
|
|
|
|
Type type = attr.getElementType();
|
|
|
|
unsigned bitwidth = type.isInteger(1) ? 8 : type.getIntOrFloatBitWidth();
|
|
|
|
unsigned byteSize = bitwidth / 8;
|
|
|
|
ArrayRef<char> data = attr.getRawData();
|
|
|
|
|
|
|
|
auto printElementAt = [&](unsigned i) {
|
|
|
|
APInt value(bitwidth, 0);
|
2022-09-01 09:49:53 -07:00
|
|
|
if (bitwidth) {
|
|
|
|
llvm::LoadIntFromMemory(
|
|
|
|
value, reinterpret_cast<const uint8_t *>(data.begin() + byteSize * i),
|
|
|
|
byteSize);
|
|
|
|
}
|
2022-08-25 16:21:28 -07:00
|
|
|
// Print the data as-is or as a float.
|
|
|
|
if (type.isIntOrIndex()) {
|
|
|
|
printDenseIntElement(value, getStream(), type);
|
|
|
|
} else {
|
2023-05-11 11:10:46 +02:00
|
|
|
APFloat fltVal(llvm::cast<FloatType>(type).getFloatSemantics(), value);
|
2022-08-25 16:21:28 -07:00
|
|
|
printFloatValue(fltVal, getStream());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
llvm::interleaveComma(llvm::seq<unsigned>(0, attr.size()), getStream(),
|
|
|
|
printElementAt);
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printType(Type type) {
|
2020-04-05 03:01:21 +00:00
|
|
|
if (!type) {
|
|
|
|
os << "<<NULL TYPE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// Try to print an alias for this type.
|
2022-09-02 21:23:47 -07:00
|
|
|
if (succeeded(printAlias(type)))
|
2020-10-30 00:30:59 -07:00
|
|
|
return;
|
2022-10-22 14:01:41 -07:00
|
|
|
return printTypeImpl(type);
|
|
|
|
}
|
2019-01-10 22:08:39 -08:00
|
|
|
|
2022-10-22 14:01:41 -07:00
|
|
|
void AsmPrinter::Impl::printTypeImpl(Type type) {
|
2020-08-12 19:28:54 -07:00
|
|
|
TypeSwitch<Type>(type)
|
|
|
|
.Case<OpaqueType>([&](OpaqueType opaqueTy) {
|
|
|
|
printDialectSymbol(os, "!", opaqueTy.getDialectNamespace(),
|
|
|
|
opaqueTy.getTypeData());
|
|
|
|
})
|
|
|
|
.Case<IndexType>([&](Type) { os << "index"; })
|
2024-09-24 08:22:48 +02:00
|
|
|
.Case<Float4E2M1FNType>([&](Type) { os << "f4E2M1FN"; })
|
2024-09-16 21:09:27 +02:00
|
|
|
.Case<Float6E2M3FNType>([&](Type) { os << "f6E2M3FN"; })
|
2024-09-10 10:41:05 +02:00
|
|
|
.Case<Float6E3M2FNType>([&](Type) { os << "f6E3M2FN"; })
|
Add APFloat and MLIR type support for fp8 (e5m2).
(Re-Apply with fixes to clang MicrosoftMangle.cpp)
This is a first step towards high level representation for fp8 types
that have been built in to hardware with near term roadmaps. Like the
BFLOAT16 type, the family of fp8 types are inspired by IEEE-754 binary
floating point formats but, due to the size limits, have been tweaked in
various ways in order to maximally use the range/precision in various
scenarios. The list of variants is small/finite and bounded by real
hardware.
This patch introduces the E5M2 FP8 format as proposed by Nvidia, ARM,
and Intel in the paper: https://arxiv.org/pdf/2209.05433.pdf
As the more conformant of the two implemented datatypes, we are plumbing
it through LLVM's APFloat type and MLIR's type system first as a
template. It will be followed by the range optimized E4M3 FP8 format
described in the paper. Since that format deviates further from the
IEEE-754 norms, it may require more debate and implementation
complexity.
Given that we see two parts of the FP8 implementation space represented
by these cases, we are recommending naming of:
* `F8M<N>` : For FP8 types that can be conceived of as following the
same rules as FP16 but with a smaller number of mantissa/exponent
bits. Including the number of mantissa bits in the type name is enough
to fully specify the type. This naming scheme is used to represent
the E5M2 type described in the paper.
* `F8M<N>F` : For FP8 types such as E4M3 which only support finite
values.
The first of these (this patch) seems fairly non-controversial. The
second is previewed here to illustrate options for extending to the
other known variant (but can be discussed in detail in the patch
which implements it).
Many conversations about these types focus on the Machine-Learning
ecosystem where they are used to represent mixed-datatype computations
at a high level. At that level (which is why we also expose them in
MLIR), it is important to retain the actual type definition so that when
lowering to actual kernels or target specific code, the correct
promotions, casts and rescalings can be done as needed. We expect that
most LLVM backends will only experience these types as opaque `I8`
values that are applicable to some instructions.
MLIR does not make it particularly easy to add new floating point types
(i.e. the FloatType hierarchy is not open). Given the need to fully
model FloatTypes and make them interop with tooling, such types will
always be "heavy-weight" and it is not expected that a highly open type
system will be particularly helpful. There are also a bounded number of
floating point types in use for current and upcoming hardware, and we
can just implement them like this (perhaps looking for some cosmetic
ways to reduce the number of places that need to change). Creating a
more generic mechanism for extending floating point types seems like it
wouldn't be worth it and we should just deal with defining them one by
one on an as-needed basis when real hardware implements a new scheme.
Hopefully, with some additional production use and complete software
stacks, hardware makers will converge on a set of such types that is not
terribly divergent at the level that the compiler cares about.
(I cleaned up some old formatting and sorted some items for this case:
If we converge on landing this in some form, I will NFC commit format
only changes as a separate commit)
Differential Revision: https://reviews.llvm.org/D133823
2022-07-26 19:02:37 -07:00
|
|
|
.Case<Float8E5M2Type>([&](Type) { os << "f8E5M2"; })
|
2024-07-22 23:20:28 -07:00
|
|
|
.Case<Float8E4M3Type>([&](Type) { os << "f8E4M3"; })
|
2022-11-16 10:24:24 +01:00
|
|
|
.Case<Float8E4M3FNType>([&](Type) { os << "f8E4M3FN"; })
|
2023-02-13 14:10:20 +00:00
|
|
|
.Case<Float8E5M2FNUZType>([&](Type) { os << "f8E5M2FNUZ"; })
|
|
|
|
.Case<Float8E4M3FNUZType>([&](Type) { os << "f8E4M3FNUZ"; })
|
2023-03-09 23:10:57 +00:00
|
|
|
.Case<Float8E4M3B11FNUZType>([&](Type) { os << "f8E4M3B11FNUZ"; })
|
2024-08-02 00:22:11 -07:00
|
|
|
.Case<Float8E3M4Type>([&](Type) { os << "f8E3M4"; })
|
2024-10-04 09:23:12 +02:00
|
|
|
.Case<Float8E8M0FNUType>([&](Type) { os << "f8E8M0FNU"; })
|
2020-08-12 19:28:54 -07:00
|
|
|
.Case<BFloat16Type>([&](Type) { os << "bf16"; })
|
|
|
|
.Case<Float16Type>([&](Type) { os << "f16"; })
|
2023-07-06 08:56:05 -07:00
|
|
|
.Case<FloatTF32Type>([&](Type) { os << "tf32"; })
|
2020-08-12 19:28:54 -07:00
|
|
|
.Case<Float32Type>([&](Type) { os << "f32"; })
|
|
|
|
.Case<Float64Type>([&](Type) { os << "f64"; })
|
2021-01-15 10:29:37 -05:00
|
|
|
.Case<Float80Type>([&](Type) { os << "f80"; })
|
|
|
|
.Case<Float128Type>([&](Type) { os << "f128"; })
|
2020-08-12 19:28:54 -07:00
|
|
|
.Case<IntegerType>([&](IntegerType integerTy) {
|
|
|
|
if (integerTy.isSigned())
|
|
|
|
os << 's';
|
|
|
|
else if (integerTy.isUnsigned())
|
|
|
|
os << 'u';
|
|
|
|
os << 'i' << integerTy.getWidth();
|
|
|
|
})
|
|
|
|
.Case<FunctionType>([&](FunctionType funcTy) {
|
|
|
|
os << '(';
|
|
|
|
interleaveComma(funcTy.getInputs(), [&](Type ty) { printType(ty); });
|
|
|
|
os << ") -> ";
|
|
|
|
ArrayRef<Type> results = funcTy.getResults();
|
2023-05-11 11:10:46 +02:00
|
|
|
if (results.size() == 1 && !llvm::isa<FunctionType>(results[0])) {
|
2021-10-11 14:52:06 +03:00
|
|
|
printType(results[0]);
|
2020-08-12 19:28:54 -07:00
|
|
|
} else {
|
|
|
|
os << '(';
|
|
|
|
interleaveComma(results, [&](Type ty) { printType(ty); });
|
|
|
|
os << ')';
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.Case<VectorType>([&](VectorType vectorTy) {
|
2023-06-19 13:01:11 +01:00
|
|
|
auto scalableDims = vectorTy.getScalableDims();
|
2020-08-12 19:28:54 -07:00
|
|
|
os << "vector<";
|
2021-10-12 14:26:01 +01:00
|
|
|
auto vShape = vectorTy.getShape();
|
|
|
|
unsigned lastDim = vShape.size();
|
|
|
|
unsigned dimIdx = 0;
|
2023-06-19 13:01:11 +01:00
|
|
|
for (dimIdx = 0; dimIdx < lastDim; dimIdx++) {
|
|
|
|
if (!scalableDims.empty() && scalableDims[dimIdx])
|
|
|
|
os << '[';
|
|
|
|
os << vShape[dimIdx];
|
|
|
|
if (!scalableDims.empty() && scalableDims[dimIdx])
|
|
|
|
os << ']';
|
|
|
|
os << 'x';
|
2021-10-12 14:26:01 +01:00
|
|
|
}
|
2021-10-11 14:52:06 +03:00
|
|
|
printType(vectorTy.getElementType());
|
|
|
|
os << '>';
|
2020-08-12 19:28:54 -07:00
|
|
|
})
|
|
|
|
.Case<RankedTensorType>([&](RankedTensorType tensorTy) {
|
|
|
|
os << "tensor<";
|
2023-12-08 11:34:44 -08:00
|
|
|
printDimensionList(tensorTy.getShape());
|
|
|
|
if (!tensorTy.getShape().empty())
|
2020-08-12 19:28:54 -07:00
|
|
|
os << 'x';
|
2021-10-11 14:52:06 +03:00
|
|
|
printType(tensorTy.getElementType());
|
[mlir] introduce "encoding" attribute to tensor type
This CL introduces a generic attribute (called "encoding") on tensors.
The attribute currently does not carry any concrete information, but the type
system already correctly determines that tensor<8xi1,123> != tensor<8xi1,321>.
The attribute will be given meaning through an interface in subsequent CLs.
See ongoing discussion on discourse:
[RFC] Introduce a sparse tensor type to core MLIR
https://llvm.discourse.group/t/rfc-introduce-a-sparse-tensor-type-to-core-mlir/2944
A sparse tensor will look something like this:
```
// named alias with all properties we hold dear:
#CSR = {
// individual named attributes
}
// actual sparse tensor type:
tensor<?x?xf64, #CSR>
```
I see the following rough 5 step plan going forward:
(1) introduce this format attribute in this CL, currently still empty
(2) introduce attribute interface that gives it "meaning", focused on sparse in first phase
(3) rewrite sparse compiler to use new type, remove linalg interface and "glue"
(4) teach passes to deal with new attribute, by rejecting/asserting on non-empty attribute as simplest solution, or doing meaningful rewrite in the longer run
(5) add FE support, document, test, publicize new features, extend "format" meaning to other domains if useful
Reviewed By: stellaraccident, bondhugula
Differential Revision: https://reviews.llvm.org/D99548
2021-04-12 09:28:41 -07:00
|
|
|
// Only print the encoding attribute value if set.
|
|
|
|
if (tensorTy.getEncoding()) {
|
|
|
|
os << ", ";
|
|
|
|
printAttribute(tensorTy.getEncoding());
|
|
|
|
}
|
|
|
|
os << '>';
|
2020-08-12 19:28:54 -07:00
|
|
|
})
|
|
|
|
.Case<UnrankedTensorType>([&](UnrankedTensorType tensorTy) {
|
|
|
|
os << "tensor<*x";
|
|
|
|
printType(tensorTy.getElementType());
|
|
|
|
os << '>';
|
|
|
|
})
|
|
|
|
.Case<MemRefType>([&](MemRefType memrefTy) {
|
|
|
|
os << "memref<";
|
2023-12-08 11:34:44 -08:00
|
|
|
printDimensionList(memrefTy.getShape());
|
|
|
|
if (!memrefTy.getShape().empty())
|
2020-08-12 19:28:54 -07:00
|
|
|
os << 'x';
|
|
|
|
printType(memrefTy.getElementType());
|
2022-09-15 18:29:38 +02:00
|
|
|
MemRefLayoutAttrInterface layout = memrefTy.getLayout();
|
2023-05-11 11:10:46 +02:00
|
|
|
if (!llvm::isa<AffineMapAttr>(layout) || !layout.isIdentity()) {
|
2020-08-12 19:28:54 -07:00
|
|
|
os << ", ";
|
2021-10-11 18:25:14 +03:00
|
|
|
printAttribute(memrefTy.getLayout(), AttrTypeElision::May);
|
2020-08-12 19:28:54 -07:00
|
|
|
}
|
|
|
|
// Only print the memory space if it is the non-default one.
|
2021-02-05 16:53:00 +03:00
|
|
|
if (memrefTy.getMemorySpace()) {
|
|
|
|
os << ", ";
|
|
|
|
printAttribute(memrefTy.getMemorySpace(), AttrTypeElision::May);
|
|
|
|
}
|
2020-08-12 19:28:54 -07:00
|
|
|
os << '>';
|
|
|
|
})
|
|
|
|
.Case<UnrankedMemRefType>([&](UnrankedMemRefType memrefTy) {
|
|
|
|
os << "memref<*x";
|
|
|
|
printType(memrefTy.getElementType());
|
2020-08-17 20:25:28 +02:00
|
|
|
// Only print the memory space if it is the non-default one.
|
2021-02-05 16:53:00 +03:00
|
|
|
if (memrefTy.getMemorySpace()) {
|
|
|
|
os << ", ";
|
|
|
|
printAttribute(memrefTy.getMemorySpace(), AttrTypeElision::May);
|
|
|
|
}
|
2020-08-12 19:28:54 -07:00
|
|
|
os << '>';
|
|
|
|
})
|
|
|
|
.Case<ComplexType>([&](ComplexType complexTy) {
|
|
|
|
os << "complex<";
|
|
|
|
printType(complexTy.getElementType());
|
|
|
|
os << '>';
|
|
|
|
})
|
|
|
|
.Case<TupleType>([&](TupleType tupleTy) {
|
|
|
|
os << "tuple<";
|
|
|
|
interleaveComma(tupleTy.getTypes(),
|
|
|
|
[&](Type type) { printType(type); });
|
|
|
|
os << '>';
|
|
|
|
})
|
|
|
|
.Case<NoneType>([&](Type) { os << "none"; })
|
|
|
|
.Default([&](Type type) { return printDialectType(type); });
|
2018-08-07 14:24:38 -07:00
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs,
|
|
|
|
bool withKeyword) {
|
2018-09-18 16:36:26 -07:00
|
|
|
// If there are no attributes, then there is nothing to be done.
|
|
|
|
if (attrs.empty())
|
|
|
|
return;
|
|
|
|
|
2021-03-05 12:42:24 -08:00
|
|
|
// Functor used to print a filtered attribute list.
|
|
|
|
auto printFilteredAttributesFn = [&](auto filteredAttrs) {
|
|
|
|
// Print the 'attributes' keyword if necessary.
|
|
|
|
if (withKeyword)
|
|
|
|
os << " attributes";
|
2018-09-18 16:36:26 -07:00
|
|
|
|
2021-03-05 12:42:24 -08:00
|
|
|
// Otherwise, print them all out in braces.
|
|
|
|
os << " {";
|
|
|
|
interleaveComma(filteredAttrs,
|
|
|
|
[&](NamedAttribute attr) { printNamedAttribute(attr); });
|
|
|
|
os << '}';
|
|
|
|
};
|
2018-09-18 16:36:26 -07:00
|
|
|
|
2021-03-05 12:42:24 -08:00
|
|
|
// If no attributes are elided, we can directly print with no filtering.
|
|
|
|
if (elidedAttrs.empty())
|
|
|
|
return printFilteredAttributesFn(attrs);
|
2019-11-05 17:58:16 -08:00
|
|
|
|
2021-03-05 12:42:24 -08:00
|
|
|
// Otherwise, filter out any attributes that shouldn't be included.
|
|
|
|
llvm::SmallDenseSet<StringRef> elidedAttrsSet(elidedAttrs.begin(),
|
|
|
|
elidedAttrs.end());
|
|
|
|
auto filteredAttrs = llvm::make_filter_range(attrs, [&](NamedAttribute attr) {
|
2021-11-18 05:23:32 +00:00
|
|
|
return !elidedAttrsSet.contains(attr.getName().strref());
|
2021-03-05 12:42:24 -08:00
|
|
|
});
|
|
|
|
if (!filteredAttrs.empty())
|
|
|
|
printFilteredAttributesFn(filteredAttrs);
|
2020-03-11 13:22:19 -07:00
|
|
|
}
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printNamedAttribute(NamedAttribute attr) {
|
2021-10-12 13:29:29 -07:00
|
|
|
// Print the name without quotes if possible.
|
2021-11-18 05:23:32 +00:00
|
|
|
::printKeywordOrString(attr.getName().strref(), os);
|
2019-04-25 09:56:09 -07:00
|
|
|
|
2020-03-11 13:22:19 -07:00
|
|
|
// Pretty printing elides the attribute value for unit attributes.
|
2023-05-11 11:10:46 +02:00
|
|
|
if (llvm::isa<UnitAttr>(attr.getValue()))
|
2020-03-11 13:22:19 -07:00
|
|
|
return;
|
2019-04-25 09:56:09 -07:00
|
|
|
|
2020-03-11 13:22:19 -07:00
|
|
|
os << " = ";
|
2021-11-18 05:23:32 +00:00
|
|
|
printAttribute(attr.getValue());
|
2018-09-18 16:36:26 -07:00
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printDialectAttribute(Attribute attr) {
|
2020-01-09 12:39:26 -08:00
|
|
|
auto &dialect = attr.getDialect();
|
2019-11-20 10:19:01 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Ask the dialect to serialize the attribute to a string.
|
|
|
|
std::string attrName;
|
|
|
|
{
|
|
|
|
llvm::raw_string_ostream attrNameStr(attrName);
|
2022-09-02 21:23:47 -07:00
|
|
|
Impl subPrinter(attrNameStr, state);
|
2021-09-24 19:56:01 +00:00
|
|
|
DialectAsmPrinter printer(subPrinter);
|
2020-01-09 12:39:26 -08:00
|
|
|
dialect.printAttribute(attr, printer);
|
|
|
|
}
|
|
|
|
printDialectSymbol(os, "#", dialect.getNamespace(), attrName);
|
|
|
|
}
|
2019-11-20 10:19:01 -08:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printDialectType(Type type) {
|
2020-01-09 12:39:26 -08:00
|
|
|
auto &dialect = type.getDialect();
|
2018-07-22 15:45:24 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Ask the dialect to serialize the type to a string.
|
|
|
|
std::string typeName;
|
|
|
|
{
|
|
|
|
llvm::raw_string_ostream typeNameStr(typeName);
|
2022-09-02 21:23:47 -07:00
|
|
|
Impl subPrinter(typeNameStr, state);
|
2021-09-24 19:56:01 +00:00
|
|
|
DialectAsmPrinter printer(subPrinter);
|
2020-01-09 12:39:26 -08:00
|
|
|
dialect.printType(type, printer);
|
2018-07-22 15:45:24 -07:00
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
printDialectSymbol(os, "!", dialect.getNamespace(), typeName);
|
|
|
|
}
|
2018-07-27 11:10:12 -07:00
|
|
|
|
2022-05-24 01:55:27 -07:00
|
|
|
void AsmPrinter::Impl::printEscapedString(StringRef str) {
|
|
|
|
os << "\"";
|
|
|
|
llvm::printEscapedString(str, os);
|
|
|
|
os << "\"";
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsmPrinter::Impl::printHexString(StringRef str) {
|
|
|
|
os << "\"0x" << llvm::toHex(str) << "\"";
|
|
|
|
}
|
|
|
|
void AsmPrinter::Impl::printHexString(ArrayRef<char> data) {
|
|
|
|
printHexString(StringRef(data.data(), data.size()));
|
|
|
|
}
|
|
|
|
|
2023-09-04 18:19:18 +02:00
|
|
|
LogicalResult AsmPrinter::Impl::pushCyclicPrinting(const void *opaquePointer) {
|
|
|
|
return state.pushCyclicPrinting(opaquePointer);
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsmPrinter::Impl::popCyclicPrinting() { state.popCyclicPrinting(); }
|
|
|
|
|
2023-12-08 11:34:44 -08:00
|
|
|
void AsmPrinter::Impl::printDimensionList(ArrayRef<int64_t> shape) {
|
|
|
|
detail::printDimensionList(os, shape);
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
// AsmPrinter
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
2021-12-22 00:19:53 +00:00
|
|
|
AsmPrinter::~AsmPrinter() = default;
|
2021-09-24 19:56:01 +00:00
|
|
|
|
|
|
|
raw_ostream &AsmPrinter::getStream() const {
|
|
|
|
assert(impl && "expected AsmPrinter::getStream to be overriden");
|
|
|
|
return impl->getStream();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Print the given floating point value in a stablized form.
|
|
|
|
void AsmPrinter::printFloat(const APFloat &value) {
|
|
|
|
assert(impl && "expected AsmPrinter::printFloat to be overriden");
|
|
|
|
printFloatValue(value, impl->getStream());
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsmPrinter::printType(Type type) {
|
|
|
|
assert(impl && "expected AsmPrinter::printType to be overriden");
|
|
|
|
impl->printType(type);
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsmPrinter::printAttribute(Attribute attr) {
|
|
|
|
assert(impl && "expected AsmPrinter::printAttribute to be overriden");
|
|
|
|
impl->printAttribute(attr);
|
|
|
|
}
|
|
|
|
|
2021-12-08 01:24:51 +00:00
|
|
|
LogicalResult AsmPrinter::printAlias(Attribute attr) {
|
|
|
|
assert(impl && "expected AsmPrinter::printAlias to be overriden");
|
|
|
|
return impl->printAlias(attr);
|
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult AsmPrinter::printAlias(Type type) {
|
|
|
|
assert(impl && "expected AsmPrinter::printAlias to be overriden");
|
|
|
|
return impl->printAlias(type);
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::printAttributeWithoutType(Attribute attr) {
|
|
|
|
assert(impl &&
|
|
|
|
"expected AsmPrinter::printAttributeWithoutType to be overriden");
|
|
|
|
impl->printAttribute(attr, Impl::AttrTypeElision::Must);
|
|
|
|
}
|
|
|
|
|
2021-10-12 13:29:29 -07:00
|
|
|
void AsmPrinter::printKeywordOrString(StringRef keyword) {
|
|
|
|
assert(impl && "expected AsmPrinter::printKeywordOrString to be overriden");
|
|
|
|
::printKeywordOrString(keyword, impl->getStream());
|
|
|
|
}
|
|
|
|
|
2023-09-09 00:06:38 +02:00
|
|
|
void AsmPrinter::printString(StringRef keyword) {
|
|
|
|
assert(impl && "expected AsmPrinter::printString to be overriden");
|
|
|
|
*this << '"';
|
|
|
|
printEscapedString(keyword, getStream());
|
|
|
|
*this << '"';
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::printSymbolName(StringRef symbolRef) {
|
|
|
|
assert(impl && "expected AsmPrinter::printSymbolName to be overriden");
|
|
|
|
::printSymbolReference(symbolRef, impl->getStream());
|
|
|
|
}
|
|
|
|
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
void AsmPrinter::printResourceHandle(const AsmDialectResourceHandle &resource) {
|
|
|
|
assert(impl && "expected AsmPrinter::printResourceHandle to be overriden");
|
|
|
|
impl->printResourceHandle(resource);
|
|
|
|
}
|
|
|
|
|
2023-12-08 11:34:44 -08:00
|
|
|
void AsmPrinter::printDimensionList(ArrayRef<int64_t> shape) {
|
|
|
|
detail::printDimensionList(getStream(), shape);
|
|
|
|
}
|
|
|
|
|
2023-09-04 18:19:18 +02:00
|
|
|
LogicalResult AsmPrinter::pushCyclicPrinting(const void *opaquePointer) {
|
|
|
|
return impl->pushCyclicPrinting(opaquePointer);
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsmPrinter::popCyclicPrinting() { impl->popCyclicPrinting(); }
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Affine expressions and maps
|
|
|
|
//===----------------------------------------------------------------------===//
|
2019-10-14 16:21:17 -07:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printAffineExpr(
|
2020-01-09 12:39:26 -08:00
|
|
|
AffineExpr expr, function_ref<void(unsigned, bool)> printValueName) {
|
|
|
|
printAffineExprInternal(expr, BindingStrength::Weak, printValueName);
|
2019-11-20 10:19:01 -08:00
|
|
|
}
|
2019-10-14 16:21:17 -07:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printAffineExprInternal(
|
2020-01-09 12:39:26 -08:00
|
|
|
AffineExpr expr, BindingStrength enclosingTightness,
|
|
|
|
function_ref<void(unsigned, bool)> printValueName) {
|
|
|
|
const char *binopSpelling = nullptr;
|
|
|
|
switch (expr.getKind()) {
|
|
|
|
case AffineExprKind::SymbolId: {
|
2023-11-14 13:01:19 +08:00
|
|
|
unsigned pos = cast<AffineSymbolExpr>(expr).getPosition();
|
2020-01-09 12:39:26 -08:00
|
|
|
if (printValueName)
|
|
|
|
printValueName(pos, /*isSymbol=*/true);
|
|
|
|
else
|
|
|
|
os << 's' << pos;
|
2019-11-20 10:19:01 -08:00
|
|
|
return;
|
2018-07-27 11:10:12 -07:00
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
case AffineExprKind::DimId: {
|
2023-11-14 13:01:19 +08:00
|
|
|
unsigned pos = cast<AffineDimExpr>(expr).getPosition();
|
2020-01-09 12:39:26 -08:00
|
|
|
if (printValueName)
|
|
|
|
printValueName(pos, /*isSymbol=*/false);
|
|
|
|
else
|
|
|
|
os << 'd' << pos;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
case AffineExprKind::Constant:
|
2023-11-14 13:01:19 +08:00
|
|
|
os << cast<AffineConstantExpr>(expr).getValue();
|
2020-01-09 12:39:26 -08:00
|
|
|
return;
|
|
|
|
case AffineExprKind::Add:
|
|
|
|
binopSpelling = " + ";
|
|
|
|
break;
|
|
|
|
case AffineExprKind::Mul:
|
|
|
|
binopSpelling = " * ";
|
|
|
|
break;
|
|
|
|
case AffineExprKind::FloorDiv:
|
|
|
|
binopSpelling = " floordiv ";
|
|
|
|
break;
|
|
|
|
case AffineExprKind::CeilDiv:
|
|
|
|
binopSpelling = " ceildiv ";
|
|
|
|
break;
|
|
|
|
case AffineExprKind::Mod:
|
|
|
|
binopSpelling = " mod ";
|
|
|
|
break;
|
|
|
|
}
|
2018-06-23 16:03:42 -07:00
|
|
|
|
2023-11-14 13:01:19 +08:00
|
|
|
auto binOp = cast<AffineBinaryOpExpr>(expr);
|
2020-01-09 12:39:26 -08:00
|
|
|
AffineExpr lhsExpr = binOp.getLHS();
|
|
|
|
AffineExpr rhsExpr = binOp.getRHS();
|
2018-06-23 16:03:42 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Handle tightly binding binary operators.
|
|
|
|
if (binOp.getKind() != AffineExprKind::Add) {
|
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << '(';
|
|
|
|
|
|
|
|
// Pretty print multiplication with -1.
|
2023-11-14 13:01:19 +08:00
|
|
|
auto rhsConst = dyn_cast<AffineConstantExpr>(rhsExpr);
|
2020-01-09 12:39:26 -08:00
|
|
|
if (rhsConst && binOp.getKind() == AffineExprKind::Mul &&
|
|
|
|
rhsConst.getValue() == -1) {
|
|
|
|
os << "-";
|
|
|
|
printAffineExprInternal(lhsExpr, BindingStrength::Strong, printValueName);
|
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << ')';
|
|
|
|
return;
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
2019-07-09 10:40:29 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
printAffineExprInternal(lhsExpr, BindingStrength::Strong, printValueName);
|
2018-07-26 18:09:20 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
os << binopSpelling;
|
|
|
|
printAffineExprInternal(rhsExpr, BindingStrength::Strong, printValueName);
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
2018-12-28 11:41:56 -08:00
|
|
|
os << ')';
|
2020-01-09 12:39:26 -08:00
|
|
|
return;
|
|
|
|
}
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Print out special "pretty" forms for add.
|
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << '(';
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Pretty print addition to a product that has a negative operand as a
|
|
|
|
// subtraction.
|
2023-11-14 13:01:19 +08:00
|
|
|
if (auto rhs = dyn_cast<AffineBinaryOpExpr>(rhsExpr)) {
|
2020-01-09 12:39:26 -08:00
|
|
|
if (rhs.getKind() == AffineExprKind::Mul) {
|
|
|
|
AffineExpr rrhsExpr = rhs.getRHS();
|
2023-11-14 13:01:19 +08:00
|
|
|
if (auto rrhs = dyn_cast<AffineConstantExpr>(rrhsExpr)) {
|
2020-01-09 12:39:26 -08:00
|
|
|
if (rrhs.getValue() == -1) {
|
|
|
|
printAffineExprInternal(lhsExpr, BindingStrength::Weak,
|
|
|
|
printValueName);
|
|
|
|
os << " - ";
|
|
|
|
if (rhs.getLHS().getKind() == AffineExprKind::Add) {
|
|
|
|
printAffineExprInternal(rhs.getLHS(), BindingStrength::Strong,
|
|
|
|
printValueName);
|
|
|
|
} else {
|
|
|
|
printAffineExprInternal(rhs.getLHS(), BindingStrength::Weak,
|
|
|
|
printValueName);
|
|
|
|
}
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << ')';
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (rrhs.getValue() < -1) {
|
|
|
|
printAffineExprInternal(lhsExpr, BindingStrength::Weak,
|
|
|
|
printValueName);
|
|
|
|
os << " - ";
|
|
|
|
printAffineExprInternal(rhs.getLHS(), BindingStrength::Strong,
|
|
|
|
printValueName);
|
|
|
|
os << " * " << -rrhs.getValue();
|
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << ')';
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Pretty print addition to a negative number as a subtraction.
|
2023-11-14 13:01:19 +08:00
|
|
|
if (auto rhsConst = dyn_cast<AffineConstantExpr>(rhsExpr)) {
|
2020-01-09 12:39:26 -08:00
|
|
|
if (rhsConst.getValue() < 0) {
|
|
|
|
printAffineExprInternal(lhsExpr, BindingStrength::Weak, printValueName);
|
|
|
|
os << " - " << -rhsConst.getValue();
|
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << ')';
|
|
|
|
return;
|
|
|
|
}
|
2018-07-15 00:06:54 -07:00
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
printAffineExprInternal(lhsExpr, BindingStrength::Weak, printValueName);
|
|
|
|
|
|
|
|
os << " + ";
|
|
|
|
printAffineExprInternal(rhsExpr, BindingStrength::Weak, printValueName);
|
|
|
|
|
|
|
|
if (enclosingTightness == BindingStrength::Strong)
|
|
|
|
os << ')';
|
2018-07-13 13:03:13 -07:00
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printAffineConstraint(AffineExpr expr, bool isEq) {
|
2020-01-09 12:39:26 -08:00
|
|
|
printAffineExprInternal(expr, BindingStrength::Weak);
|
|
|
|
isEq ? os << " == 0" : os << " >= 0";
|
2018-07-20 09:35:47 -07:00
|
|
|
}
|
2018-07-03 17:51:28 -07:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printAffineMap(AffineMap map) {
|
2020-01-09 12:39:26 -08:00
|
|
|
// Dimension identifiers.
|
|
|
|
os << '(';
|
|
|
|
for (int i = 0; i < (int)map.getNumDims() - 1; ++i)
|
|
|
|
os << 'd' << i << ", ";
|
|
|
|
if (map.getNumDims() >= 1)
|
|
|
|
os << 'd' << map.getNumDims() - 1;
|
|
|
|
os << ')';
|
2019-11-20 10:19:01 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Symbolic identifiers.
|
|
|
|
if (map.getNumSymbols() != 0) {
|
|
|
|
os << '[';
|
|
|
|
for (unsigned i = 0; i < map.getNumSymbols() - 1; ++i)
|
|
|
|
os << 's' << i << ", ";
|
|
|
|
if (map.getNumSymbols() >= 1)
|
|
|
|
os << 's' << map.getNumSymbols() - 1;
|
|
|
|
os << ']';
|
2019-11-20 10:19:01 -08:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Result affine expressions.
|
|
|
|
os << " -> (";
|
|
|
|
interleaveComma(map.getResults(),
|
|
|
|
[&](AffineExpr expr) { printAffineExpr(expr); });
|
|
|
|
os << ')';
|
|
|
|
}
|
2019-11-20 10:19:01 -08:00
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printIntegerSet(IntegerSet set) {
|
2020-01-09 12:39:26 -08:00
|
|
|
// Dimension identifiers.
|
|
|
|
os << '(';
|
|
|
|
for (unsigned i = 1; i < set.getNumDims(); ++i)
|
|
|
|
os << 'd' << i - 1 << ", ";
|
|
|
|
if (set.getNumDims() >= 1)
|
|
|
|
os << 'd' << set.getNumDims() - 1;
|
|
|
|
os << ')';
|
|
|
|
|
|
|
|
// Symbolic identifiers.
|
|
|
|
if (set.getNumSymbols() != 0) {
|
|
|
|
os << '[';
|
|
|
|
for (unsigned i = 0; i < set.getNumSymbols() - 1; ++i)
|
|
|
|
os << 's' << i << ", ";
|
|
|
|
if (set.getNumSymbols() >= 1)
|
|
|
|
os << 's' << set.getNumSymbols() - 1;
|
|
|
|
os << ']';
|
2019-11-20 10:19:01 -08:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// Print constraints.
|
|
|
|
os << " : (";
|
|
|
|
int numConstraints = set.getNumConstraints();
|
|
|
|
for (int i = 1; i < numConstraints; ++i) {
|
|
|
|
printAffineConstraint(set.getConstraint(i - 1), set.isEq(i - 1));
|
|
|
|
os << ", ";
|
|
|
|
}
|
|
|
|
if (numConstraints >= 1)
|
|
|
|
printAffineConstraint(set.getConstraint(numConstraints - 1),
|
|
|
|
set.isEq(numConstraints - 1));
|
|
|
|
os << ')';
|
2019-11-20 10:19:01 -08:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// OperationPrinter
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
/// This class contains the logic for printing operations, regions, and blocks.
|
2021-09-24 19:56:01 +00:00
|
|
|
class OperationPrinter : public AsmPrinter::Impl, private OpAsmPrinter {
|
2020-01-09 12:39:26 -08:00
|
|
|
public:
|
2021-09-24 19:56:01 +00:00
|
|
|
using Impl = AsmPrinter::Impl;
|
|
|
|
using Impl::printType;
|
|
|
|
|
2022-02-15 17:09:08 -08:00
|
|
|
explicit OperationPrinter(raw_ostream &os, AsmStateImpl &state)
|
2022-09-02 21:23:47 -07:00
|
|
|
: Impl(os, state), OpAsmPrinter(static_cast<Impl &>(*this)) {}
|
2019-08-29 12:14:02 -07:00
|
|
|
|
2020-12-03 15:46:23 -08:00
|
|
|
/// Print the given top-level operation.
|
|
|
|
void printTopLevelOperation(Operation *op);
|
|
|
|
|
2022-10-05 18:31:22 +00:00
|
|
|
/// Print the given operation, including its left-hand side and its right-hand
|
|
|
|
/// side, with its indent and location.
|
|
|
|
void printFullOpWithIndentAndLoc(Operation *op);
|
|
|
|
/// Print the given operation, including its left-hand side and its right-hand
|
|
|
|
/// side, but not including indentation and location.
|
|
|
|
void printFullOp(Operation *op);
|
|
|
|
/// Print the right-hand size of the given operation in the custom or generic
|
|
|
|
/// form.
|
|
|
|
void printCustomOrGenericOp(Operation *op) override;
|
|
|
|
/// Print the right-hand side of the given operation in the generic form.
|
2021-08-28 03:03:15 +00:00
|
|
|
void printGenericOp(Operation *op, bool printOpName) override;
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the name of the given block.
|
|
|
|
void printBlockName(Block *block);
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the given block. If 'printBlockArgs' is false, the arguments of the
|
|
|
|
/// block are not printed. If 'printBlockTerminator' is false, the terminator
|
|
|
|
/// operation of the block is not printed.
|
|
|
|
void print(Block *block, bool printBlockArgs = true,
|
|
|
|
bool printBlockTerminator = true);
|
|
|
|
|
|
|
|
/// Print the ID of the given value, optionally with its result number.
|
Add support for custom op parser/printer hooks to know about result names.
Summary:
This allows the custom parser/printer hooks to do interesting things with
the SSA names. This patch:
- Adds a new 'getResultName' method to OpAsmParser that allows a parser
implementation to get information about its result names, along with
a getNumResults() method that allows op parser impls to know how many
results are expected.
- Adds a OpAsmPrinter::printOperand overload that takes an explicit stream.
- Adds a test.string_attr_pretty_name operation that uses these hooks to
do fancy things with the result name.
Reviewers: rriddle!
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76205
2020-03-15 17:13:59 -07:00
|
|
|
void printValueID(Value value, bool printResultNo = true,
|
|
|
|
raw_ostream *streamOverride = nullptr) const;
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// Print the ID of the given operation.
|
|
|
|
void printOperationID(Operation *op,
|
|
|
|
raw_ostream *streamOverride = nullptr) const;
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
// OpAsmPrinter methods
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
2022-09-29 14:43:08 -07:00
|
|
|
/// Print a loc(...) specifier if printing debug info is enabled. Locations
|
|
|
|
/// may be deferred with an alias.
|
|
|
|
void printOptionalLocationSpecifier(Location loc) override {
|
|
|
|
printTrailingLocation(loc);
|
|
|
|
}
|
|
|
|
|
2020-12-14 11:53:34 -08:00
|
|
|
/// Print a newline and indent the printer to the start of the current
|
|
|
|
/// operation.
|
|
|
|
void printNewline() override {
|
|
|
|
os << newLine;
|
|
|
|
os.indent(currentIndent);
|
|
|
|
}
|
|
|
|
|
2022-10-27 09:39:52 +02:00
|
|
|
/// Increase indentation.
|
|
|
|
void increaseIndent() override { currentIndent += indentWidth; }
|
|
|
|
|
|
|
|
/// Decrease indentation.
|
|
|
|
void decreaseIndent() override { currentIndent -= indentWidth; }
|
|
|
|
|
2021-05-23 14:08:31 -07:00
|
|
|
/// Print a block argument in the usual format of:
|
|
|
|
/// %ssaName : type {attr1=42} loc("here")
|
|
|
|
/// where location printing is controlled by the standard internal option.
|
|
|
|
/// You may pass omitType=true to not print a type, and pass an empty
|
|
|
|
/// attribute list if you don't care for attributes.
|
|
|
|
void printRegionArgument(BlockArgument arg,
|
|
|
|
ArrayRef<NamedAttribute> argAttrs = {},
|
|
|
|
bool omitType = false) override;
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the ID for the given value.
|
|
|
|
void printOperand(Value value) override { printValueID(value); }
|
Add support for custom op parser/printer hooks to know about result names.
Summary:
This allows the custom parser/printer hooks to do interesting things with
the SSA names. This patch:
- Adds a new 'getResultName' method to OpAsmParser that allows a parser
implementation to get information about its result names, along with
a getNumResults() method that allows op parser impls to know how many
results are expected.
- Adds a OpAsmPrinter::printOperand overload that takes an explicit stream.
- Adds a test.string_attr_pretty_name operation that uses these hooks to
do fancy things with the result name.
Reviewers: rriddle!
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76205
2020-03-15 17:13:59 -07:00
|
|
|
void printOperand(Value value, raw_ostream &os) override {
|
|
|
|
printValueID(value, /*printResultNo=*/true, &os);
|
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
/// Print an optional attribute dictionary with a given set of elided values.
|
|
|
|
void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs = {}) override {
|
2021-09-24 19:56:01 +00:00
|
|
|
Impl::printOptionalAttrDict(attrs, elidedAttrs);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
void printOptionalAttrDictWithKeyword(
|
|
|
|
ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs = {}) override {
|
2021-09-24 19:56:01 +00:00
|
|
|
Impl::printOptionalAttrDict(attrs, elidedAttrs,
|
|
|
|
/*withKeyword=*/true);
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
|
2020-03-05 12:48:28 -08:00
|
|
|
/// Print the given successor.
|
|
|
|
void printSuccessor(Block *successor) override;
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print an operation successor with the operands used for the block
|
|
|
|
/// arguments.
|
2020-03-05 12:48:28 -08:00
|
|
|
void printSuccessorAndUseList(Block *successor,
|
|
|
|
ValueRange succOperands) override;
|
2019-08-23 10:35:24 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the given region.
|
|
|
|
void printRegion(Region ®ion, bool printEntryBlockArgs,
|
2021-03-11 23:58:02 +00:00
|
|
|
bool printBlockTerminators, bool printEmptyBlock) override;
|
2019-08-23 10:35:24 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Renumber the arguments for the specified region to the same names as the
|
|
|
|
/// SSA values in namesToUse. This may only be used for IsolatedFromAbove
|
|
|
|
/// operations. If any entry in namesToUse is null, the corresponding
|
|
|
|
/// argument name is left alone.
|
|
|
|
void shadowRegionArgs(Region ®ion, ValueRange namesToUse) override {
|
2022-09-02 21:23:47 -07:00
|
|
|
state.getSSANameState().shadowRegionArgs(region, namesToUse);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
2019-08-23 10:35:24 -07:00
|
|
|
|
[mlir] NFC: fix trivial typo in source files
Summary: fix trivial typos in the source files
Reviewers: mravishankar, antiagainst, nicolasvasilache, herhut, rriddle, aartbik
Reviewed By: antiagainst, rriddle
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, csigg, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, bader, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76876
2020-03-27 03:51:37 +09:00
|
|
|
/// Print the given affine map with the symbol and dimension operands printed
|
2020-01-09 12:39:26 -08:00
|
|
|
/// inline with the map.
|
|
|
|
void printAffineMapOfSSAIds(AffineMapAttr mapAttr,
|
|
|
|
ValueRange operands) override;
|
2019-08-23 10:35:24 -07:00
|
|
|
|
2021-04-29 13:15:21 +02:00
|
|
|
/// Print the given affine expression with the symbol and dimension operands
|
|
|
|
/// printed inline with the expression.
|
|
|
|
void printAffineExprOfSSAIds(AffineExpr expr, ValueRange dimOperands,
|
|
|
|
ValueRange symOperands) override;
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// Print users of this operation or id of this operation if it has no result.
|
|
|
|
void printUsersComment(Operation *op);
|
|
|
|
|
|
|
|
/// Print users of this block arg.
|
|
|
|
void printUsersComment(BlockArgument arg);
|
|
|
|
|
|
|
|
/// Print the users of a value.
|
|
|
|
void printValueUsers(Value value);
|
|
|
|
|
|
|
|
/// Print either the ids of the result values or the id of the operation if
|
|
|
|
/// the operation has no results.
|
|
|
|
void printUserIDs(Operation *user, bool prefixComma = false);
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
private:
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
/// This class represents a resource builder implementation for the MLIR
|
|
|
|
/// textual assembly format.
|
|
|
|
class ResourceBuilder : public AsmResourceBuilder {
|
|
|
|
public:
|
|
|
|
using ValueFn = function_ref<void(raw_ostream &)>;
|
|
|
|
using PrintFn = function_ref<void(StringRef, ValueFn)>;
|
|
|
|
|
2023-08-23 10:51:13 -07:00
|
|
|
ResourceBuilder(PrintFn printFn) : printFn(printFn) {}
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
~ResourceBuilder() override = default;
|
|
|
|
|
|
|
|
void buildBool(StringRef key, bool data) final {
|
2023-08-23 16:54:18 +00:00
|
|
|
printFn(key, [&](raw_ostream &os) { os << (data ? "true" : "false"); });
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
void buildString(StringRef key, StringRef data) final {
|
2023-08-25 05:51:00 +00:00
|
|
|
printFn(key, [&](raw_ostream &os) {
|
|
|
|
os << "\"";
|
|
|
|
llvm::printEscapedString(data, os);
|
|
|
|
os << "\"";
|
|
|
|
});
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
void buildBlob(StringRef key, ArrayRef<char> data,
|
|
|
|
uint32_t dataAlignment) final {
|
|
|
|
printFn(key, [&](raw_ostream &os) {
|
|
|
|
// Store the blob in a hex string containing the alignment and the data.
|
2022-07-12 09:29:07 +02:00
|
|
|
llvm::support::ulittle32_t dataAlignmentLE(dataAlignment);
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
os << "\"0x"
|
2022-07-12 09:29:07 +02:00
|
|
|
<< llvm::toHex(StringRef(reinterpret_cast<char *>(&dataAlignmentLE),
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
sizeof(dataAlignment)))
|
|
|
|
<< llvm::toHex(StringRef(data.data(), data.size())) << "\"";
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
PrintFn printFn;
|
|
|
|
};
|
|
|
|
|
|
|
|
/// Print the metadata dictionary for the file, eliding it if it is empty.
|
|
|
|
void printFileMetadataDictionary(Operation *op);
|
|
|
|
|
|
|
|
/// Print the resource sections for the file metadata dictionary.
|
|
|
|
/// `checkAddMetadataDict` is used to indicate that metadata is going to be
|
|
|
|
/// added, and the file metadata dictionary should be started if it hasn't
|
|
|
|
/// yet.
|
|
|
|
void printResourceFileMetadata(function_ref<void()> checkAddMetadataDict,
|
|
|
|
Operation *op);
|
|
|
|
|
2021-08-28 03:03:49 +00:00
|
|
|
// Contains the stack of default dialects to use when printing regions.
|
|
|
|
// A new dialect is pushed to the stack before parsing regions nested under an
|
|
|
|
// operation implementing `OpAsmOpInterface`, and popped when done. At the
|
|
|
|
// top-level we start with "builtin" as the default, so that the top-level
|
|
|
|
// `module` operation prints as-is.
|
|
|
|
SmallVector<StringRef> defaultDialectStack{"builtin"};
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// The number of spaces used for indenting nested operations.
|
|
|
|
const static unsigned indentWidth = 2;
|
2019-08-23 10:35:24 -07:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
// This is the current indentation level for nested structures.
|
|
|
|
unsigned currentIndent = 0;
|
|
|
|
};
|
2021-12-07 18:27:58 +00:00
|
|
|
} // namespace
|
2019-08-23 10:35:24 -07:00
|
|
|
|
2020-12-03 15:46:23 -08:00
|
|
|
void OperationPrinter::printTopLevelOperation(Operation *op) {
|
2020-11-12 23:33:43 -08:00
|
|
|
// Output the aliases at the top level that can't be deferred.
|
2022-10-22 14:01:41 -07:00
|
|
|
state.getAliasState().printNonDeferredAliases(*this, newLine);
|
2020-01-14 15:23:05 -08:00
|
|
|
|
|
|
|
// Print the module.
|
2022-10-05 18:31:22 +00:00
|
|
|
printFullOpWithIndentAndLoc(op);
|
2020-11-12 23:33:43 -08:00
|
|
|
os << newLine;
|
|
|
|
|
|
|
|
// Output the aliases at the top level that can be deferred.
|
2022-10-22 14:01:41 -07:00
|
|
|
state.getAliasState().printDeferredAliases(*this, newLine);
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
|
|
|
|
// Output any file level metadata.
|
|
|
|
printFileMetadataDictionary(op);
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printFileMetadataDictionary(Operation *op) {
|
|
|
|
bool sawMetadataEntry = false;
|
|
|
|
auto checkAddMetadataDict = [&] {
|
|
|
|
if (!std::exchange(sawMetadataEntry, true))
|
|
|
|
os << newLine << "{-#" << newLine;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Add the various types of metadata.
|
|
|
|
printResourceFileMetadata(checkAddMetadataDict, op);
|
|
|
|
|
|
|
|
// If the file dictionary exists, close it.
|
|
|
|
if (sawMetadataEntry)
|
|
|
|
os << newLine << "#-}" << newLine;
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printResourceFileMetadata(
|
|
|
|
function_ref<void()> checkAddMetadataDict, Operation *op) {
|
|
|
|
// Functor used to add data entries to the file metadata dictionary.
|
|
|
|
bool hadResource = false;
|
2023-07-14 19:30:17 -04:00
|
|
|
bool needResourceComma = false;
|
|
|
|
bool needEntryComma = false;
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
auto processProvider = [&](StringRef dictName, StringRef name, auto &provider,
|
|
|
|
auto &&...providerArgs) {
|
|
|
|
bool hadEntry = false;
|
|
|
|
auto printFn = [&](StringRef key, ResourceBuilder::ValueFn valueFn) {
|
|
|
|
checkAddMetadataDict();
|
|
|
|
|
2025-02-04 12:49:15 -08:00
|
|
|
std::string resourceStr;
|
|
|
|
auto printResourceStr = [&](raw_ostream &os) { os << resourceStr; };
|
2023-08-23 16:54:18 +00:00
|
|
|
std::optional<uint64_t> charLimit =
|
|
|
|
printerFlags.getLargeResourceStringLimit();
|
|
|
|
if (charLimit.has_value()) {
|
|
|
|
llvm::raw_string_ostream ss(resourceStr);
|
|
|
|
valueFn(ss);
|
|
|
|
|
2025-02-04 12:49:15 -08:00
|
|
|
// Only print entry if its string is small enough.
|
2023-08-23 16:54:18 +00:00
|
|
|
if (resourceStr.size() > charLimit.value())
|
|
|
|
return;
|
|
|
|
|
2025-02-04 12:49:15 -08:00
|
|
|
// Don't recompute resourceStr when valueFn is called below.
|
|
|
|
valueFn = printResourceStr;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Emit the top-level resource entry if we haven't yet.
|
|
|
|
if (!std::exchange(hadResource, true)) {
|
|
|
|
if (needResourceComma)
|
|
|
|
os << "," << newLine;
|
|
|
|
os << " " << dictName << "_resources: {" << newLine;
|
|
|
|
}
|
|
|
|
// Emit the parent resource entry if we haven't yet.
|
|
|
|
if (!std::exchange(hadEntry, true)) {
|
|
|
|
if (needEntryComma)
|
|
|
|
os << "," << newLine;
|
|
|
|
os << " " << name << ": {" << newLine;
|
2023-07-14 19:30:17 -04:00
|
|
|
} else {
|
2025-02-04 12:49:15 -08:00
|
|
|
os << "," << newLine;
|
2023-07-14 19:30:17 -04:00
|
|
|
}
|
2025-02-04 12:49:15 -08:00
|
|
|
os << " ";
|
|
|
|
::printKeywordOrString(key, os);
|
|
|
|
os << ": ";
|
|
|
|
// Call printResourceStr or original valueFn, depending on charLimit.
|
|
|
|
valueFn(os);
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
};
|
2023-08-23 10:51:13 -07:00
|
|
|
ResourceBuilder entryBuilder(printFn);
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
provider.buildResources(op, providerArgs..., entryBuilder);
|
|
|
|
|
2023-08-10 16:30:52 -07:00
|
|
|
needEntryComma |= hadEntry;
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
if (hadEntry)
|
|
|
|
os << newLine << " }";
|
|
|
|
};
|
|
|
|
|
|
|
|
// Print the `dialect_resources` section if we have any dialects with
|
|
|
|
// resources.
|
2022-09-02 21:23:47 -07:00
|
|
|
for (const OpAsmDialectInterface &interface : state.getDialectInterfaces()) {
|
|
|
|
auto &dialectResources = state.getDialectResources();
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
StringRef name = interface.getDialect()->getNamespace();
|
|
|
|
auto it = dialectResources.find(interface.getDialect());
|
|
|
|
if (it != dialectResources.end())
|
|
|
|
processProvider("dialect", name, interface, it->second);
|
|
|
|
else
|
|
|
|
processProvider("dialect", name, interface,
|
|
|
|
SetVector<AsmDialectResourceHandle>());
|
|
|
|
}
|
|
|
|
if (hadResource)
|
|
|
|
os << newLine << " }";
|
|
|
|
|
|
|
|
// Print the `external_resources` section if we have any external clients with
|
|
|
|
// resources.
|
2023-07-14 19:30:17 -04:00
|
|
|
needEntryComma = false;
|
|
|
|
needResourceComma = hadResource;
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
hadResource = false;
|
2022-09-02 21:23:47 -07:00
|
|
|
for (const auto &printer : state.getResourcePrinters())
|
[mlir] Allow for attaching external resources to .mlir files
This commit enables support for providing and processing external
resources within MLIR assembly formats. This is a mechanism with which
dialects, and external clients, may attach additional information when
printing IR without that information being encoded in the IR itself.
External resources are not uniqued within the MLIR context, are not
attached directly to any operation, and are solely intended to live and be
processed outside of the immediate IR. There are many potential uses of this
functionality, for example MLIR's pass crash reproducer could utilize this to
attach the pass resource executing when a crash occurs. Other types of
uses may be embedding large amounts of binary data, such as weights in ML
applications, that shouldn't be copied directly into the MLIR context, but
need to be kept adjacent to the IR.
External resources are encoded using a key-value pair nested within a
dictionary anchored by name either on a dialect, or an externally registered
entity. The key is an identifier used to disambiguate the data. The value
may be stored in various limited forms, but general encodings use a string
(human readable) or blob format (binary). Within the textual format, an
example may be of the form:
```mlir
{-#
// The `dialect_resources` section within the file-level metadata
// dictionary is used to contain any dialect resource entries.
dialect_resources: {
// Here is a dictionary anchored on "foo_dialect", which is a dialect
// namespace.
foo_dialect: {
// `some_dialect_resource` is a key to be interpreted by the dialect,
// and used to initialize/configure/etc.
some_dialect_resource: "Some important resource value"
}
},
// The `external_resources` section within the file-level metadata
// dictionary is used to contain any non-dialect resource entries.
external_resources: {
// Here is a dictionary anchored on "mlir_reproducer", which is an
// external entity representing MLIR's crash reproducer functionality.
mlir_reproducer: {
// `pipeline` is an entry that holds a crash reproducer pipeline
// resource.
pipeline: "func.func(canonicalize,cse)"
}
}
```
Differential Revision: https://reviews.llvm.org/D126446
2022-06-28 13:25:24 -07:00
|
|
|
processProvider("external", printer.getName(), printer);
|
|
|
|
if (hadResource)
|
|
|
|
os << newLine << " }";
|
2020-01-14 15:23:05 -08:00
|
|
|
}
|
|
|
|
|
2021-05-23 14:08:31 -07:00
|
|
|
/// Print a block argument in the usual format of:
|
|
|
|
/// %ssaName : type {attr1=42} loc("here")
|
|
|
|
/// where location printing is controlled by the standard internal option.
|
|
|
|
/// You may pass omitType=true to not print a type, and pass an empty
|
|
|
|
/// attribute list if you don't care for attributes.
|
|
|
|
void OperationPrinter::printRegionArgument(BlockArgument arg,
|
|
|
|
ArrayRef<NamedAttribute> argAttrs,
|
|
|
|
bool omitType) {
|
|
|
|
printOperand(arg);
|
|
|
|
if (!omitType) {
|
|
|
|
os << ": ";
|
|
|
|
printType(arg.getType());
|
|
|
|
}
|
|
|
|
printOptionalAttrDict(argAttrs);
|
|
|
|
// TODO: We should allow location aliases on block arguments.
|
|
|
|
printTrailingLocation(arg.getLoc(), /*allowAlias*/ false);
|
|
|
|
}
|
|
|
|
|
2022-10-05 18:31:22 +00:00
|
|
|
void OperationPrinter::printFullOpWithIndentAndLoc(Operation *op) {
|
2020-02-08 15:01:34 -08:00
|
|
|
// Track the location of this operation.
|
2022-09-02 21:23:47 -07:00
|
|
|
state.registerOperationLocation(op, newLine.curLine, currentIndent);
|
2020-02-08 15:01:34 -08:00
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
os.indent(currentIndent);
|
2022-10-05 18:31:22 +00:00
|
|
|
printFullOp(op);
|
2020-01-09 12:39:26 -08:00
|
|
|
printTrailingLocation(op->getLoc());
|
2022-04-22 18:52:54 +00:00
|
|
|
if (printerFlags.shouldPrintValueUsers())
|
|
|
|
printUsersComment(op);
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
|
2022-10-05 18:31:22 +00:00
|
|
|
void OperationPrinter::printFullOp(Operation *op) {
|
2019-03-28 14:58:52 -07:00
|
|
|
if (size_t numResults = op->getNumResults()) {
|
2019-11-20 10:19:01 -08:00
|
|
|
auto printResultGroup = [&](size_t resultNo, size_t resultCount) {
|
|
|
|
printValueID(op->getResult(resultNo), /*printResultNo=*/false);
|
|
|
|
if (resultCount > 1)
|
|
|
|
os << ':' << resultCount;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Check to see if this operation has multiple result groups.
|
2022-09-02 21:23:47 -07:00
|
|
|
ArrayRef<int> resultGroups = state.getSSANameState().getOpResultGroups(op);
|
2020-01-09 12:39:26 -08:00
|
|
|
if (!resultGroups.empty()) {
|
2019-11-20 10:19:01 -08:00
|
|
|
// Interleave the groups excluding the last one, this one will be handled
|
|
|
|
// separately.
|
|
|
|
interleaveComma(llvm::seq<int>(0, resultGroups.size() - 1), [&](int i) {
|
|
|
|
printResultGroup(resultGroups[i],
|
|
|
|
resultGroups[i + 1] - resultGroups[i]);
|
|
|
|
});
|
|
|
|
os << ", ";
|
|
|
|
printResultGroup(resultGroups.back(), numResults - resultGroups.back());
|
|
|
|
|
|
|
|
} else {
|
|
|
|
printResultGroup(/*resultNo=*/0, /*resultCount=*/numResults);
|
|
|
|
}
|
|
|
|
|
2018-12-28 11:41:56 -08:00
|
|
|
os << " = ";
|
|
|
|
}
|
|
|
|
|
2022-10-05 18:31:22 +00:00
|
|
|
printCustomOrGenericOp(op);
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
void OperationPrinter::printUsersComment(Operation *op) {
|
|
|
|
unsigned numResults = op->getNumResults();
|
|
|
|
if (!numResults && op->getNumOperands()) {
|
|
|
|
os << " // id: ";
|
|
|
|
printOperationID(op);
|
|
|
|
} else if (numResults && op->use_empty()) {
|
|
|
|
os << " // unused";
|
|
|
|
} else if (numResults && !op->use_empty()) {
|
|
|
|
// Print "user" if the operation has one result used to compute one other
|
|
|
|
// result, or is used in one operation with no result.
|
|
|
|
unsigned usedInNResults = 0;
|
|
|
|
unsigned usedInNOperations = 0;
|
|
|
|
SmallPtrSet<Operation *, 1> userSet;
|
|
|
|
for (Operation *user : op->getUsers()) {
|
|
|
|
if (userSet.insert(user).second) {
|
|
|
|
++usedInNOperations;
|
|
|
|
usedInNResults += user->getNumResults();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We already know that users is not empty.
|
|
|
|
bool exactlyOneUniqueUse =
|
|
|
|
usedInNResults <= 1 && usedInNOperations <= 1 && numResults == 1;
|
|
|
|
os << " // " << (exactlyOneUniqueUse ? "user" : "users") << ": ";
|
|
|
|
bool shouldPrintBrackets = numResults > 1;
|
|
|
|
auto printOpResult = [&](OpResult opResult) {
|
|
|
|
if (shouldPrintBrackets)
|
|
|
|
os << "(";
|
|
|
|
printValueUsers(opResult);
|
|
|
|
if (shouldPrintBrackets)
|
|
|
|
os << ")";
|
|
|
|
};
|
|
|
|
|
|
|
|
interleaveComma(op->getResults(), printOpResult);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printUsersComment(BlockArgument arg) {
|
|
|
|
os << "// ";
|
|
|
|
printValueID(arg);
|
|
|
|
if (arg.use_empty()) {
|
|
|
|
os << " is unused";
|
|
|
|
} else {
|
|
|
|
os << " is used by ";
|
|
|
|
printValueUsers(arg);
|
|
|
|
}
|
|
|
|
os << newLine;
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printValueUsers(Value value) {
|
|
|
|
if (value.use_empty())
|
|
|
|
os << "unused";
|
|
|
|
|
|
|
|
// One value might be used as the operand of an operation more than once.
|
|
|
|
// Only print the operations results once in that case.
|
|
|
|
SmallPtrSet<Operation *, 1> userSet;
|
2023-03-15 10:43:55 -04:00
|
|
|
for (auto [index, user] : enumerate(value.getUsers())) {
|
|
|
|
if (userSet.insert(user).second)
|
|
|
|
printUserIDs(user, index);
|
2022-04-22 18:52:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printUserIDs(Operation *user, bool prefixComma) {
|
|
|
|
if (prefixComma)
|
|
|
|
os << ", ";
|
|
|
|
|
|
|
|
if (!user->getNumResults()) {
|
|
|
|
printOperationID(user);
|
|
|
|
} else {
|
|
|
|
interleaveComma(user->getResults(),
|
|
|
|
[this](Value result) { printValueID(result); });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-05 18:31:22 +00:00
|
|
|
void OperationPrinter::printCustomOrGenericOp(Operation *op) {
|
|
|
|
// If requested, always print the generic form.
|
|
|
|
if (!printerFlags.shouldPrintGenericOpForm()) {
|
|
|
|
// Check to see if this is a known operation. If so, use the registered
|
|
|
|
// custom printer hook.
|
|
|
|
if (auto opInfo = op->getRegisteredInfo()) {
|
|
|
|
opInfo->printAssembly(op, *this, defaultDialectStack.back());
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Otherwise try to dispatch to the dialect, if available.
|
|
|
|
if (Dialect *dialect = op->getDialect()) {
|
|
|
|
if (auto opPrinter = dialect->getOperationPrinter(op)) {
|
|
|
|
// Print the op name first.
|
|
|
|
StringRef name = op->getName().getStringRef();
|
|
|
|
// Only drop the default dialect prefix when it cannot lead to
|
|
|
|
// ambiguities.
|
|
|
|
if (name.count('.') == 1)
|
|
|
|
name.consume_front((defaultDialectStack.back() + ".").str());
|
|
|
|
os << name;
|
|
|
|
|
|
|
|
// Print the rest of the op now.
|
|
|
|
opPrinter(op, *this);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise print with the generic assembly form.
|
|
|
|
printGenericOp(op, /*printOpName=*/true);
|
|
|
|
}
|
|
|
|
|
2021-08-28 03:03:15 +00:00
|
|
|
void OperationPrinter::printGenericOp(Operation *op, bool printOpName) {
|
2022-05-24 01:55:27 -07:00
|
|
|
if (printOpName)
|
|
|
|
printEscapedString(op->getName().getStringRef());
|
2021-08-28 03:03:15 +00:00
|
|
|
os << '(';
|
2020-03-05 12:48:28 -08:00
|
|
|
interleaveComma(op->getOperands(), [&](Value value) { printValueID(value); });
|
2018-12-28 11:41:56 -08:00
|
|
|
os << ')';
|
2019-01-09 12:28:30 -08:00
|
|
|
|
|
|
|
// For terminators, print the list of successors and their operands.
|
2020-03-05 12:48:28 -08:00
|
|
|
if (op->getNumSuccessors() != 0) {
|
2019-01-09 12:28:30 -08:00
|
|
|
os << '[';
|
2020-03-05 12:48:28 -08:00
|
|
|
interleaveComma(op->getSuccessors(),
|
|
|
|
[&](Block *successor) { printBlockName(successor); });
|
2019-01-09 12:28:30 -08:00
|
|
|
os << ']';
|
|
|
|
}
|
|
|
|
|
2023-02-26 10:46:01 -05:00
|
|
|
// Print the properties.
|
2023-05-02 23:41:04 -07:00
|
|
|
if (Attribute prop = op->getPropertiesAsAttribute()) {
|
|
|
|
os << " <";
|
|
|
|
Impl::printAttribute(prop);
|
|
|
|
os << '>';
|
|
|
|
}
|
2023-02-26 10:46:01 -05:00
|
|
|
|
2019-05-06 01:40:13 -07:00
|
|
|
// Print regions.
|
|
|
|
if (op->getNumRegions() != 0) {
|
|
|
|
os << " (";
|
2023-03-13 17:49:23 +01:00
|
|
|
interleaveComma(op->getRegions(), [&](Region ®ion) {
|
|
|
|
printRegion(region, /*printEntryBlockArgs=*/true,
|
|
|
|
/*printBlockTerminators=*/true, /*printEmptyBlock=*/true);
|
|
|
|
});
|
2019-05-06 01:40:13 -07:00
|
|
|
os << ')';
|
|
|
|
}
|
|
|
|
|
2024-01-03 17:31:16 +00:00
|
|
|
printOptionalAttrDict(op->getPropertiesStorage()
|
|
|
|
? llvm::to_vector(op->getDiscardableAttrs())
|
|
|
|
: op->getAttrs());
|
2018-12-28 11:41:56 -08:00
|
|
|
|
|
|
|
// Print the type signature of the operation.
|
2019-06-17 15:31:53 -07:00
|
|
|
os << " : ";
|
|
|
|
printFunctionalType(op);
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void OperationPrinter::printBlockName(Block *block) {
|
2022-09-02 21:23:47 -07:00
|
|
|
os << state.getSSANameState().getBlockInfo(block).name;
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::print(Block *block, bool printBlockArgs,
|
|
|
|
bool printBlockTerminator) {
|
|
|
|
// Print the block label and argument list if requested.
|
|
|
|
if (printBlockArgs) {
|
|
|
|
os.indent(currentIndent);
|
|
|
|
printBlockName(block);
|
|
|
|
|
|
|
|
// Print the argument list if non-empty.
|
|
|
|
if (!block->args_empty()) {
|
|
|
|
os << '(';
|
|
|
|
interleaveComma(block->getArguments(), [&](BlockArgument arg) {
|
|
|
|
printValueID(arg);
|
|
|
|
os << ": ";
|
2020-01-11 08:54:04 -08:00
|
|
|
printType(arg.getType());
|
2021-05-23 14:08:31 -07:00
|
|
|
// TODO: We should allow location aliases on block arguments.
|
|
|
|
printTrailingLocation(arg.getLoc(), /*allowAlias*/ false);
|
2020-01-09 12:39:26 -08:00
|
|
|
});
|
|
|
|
os << ')';
|
|
|
|
}
|
|
|
|
os << ':';
|
|
|
|
|
|
|
|
// Print out some context information about the predecessors of this block.
|
|
|
|
if (!block->getParent()) {
|
2020-05-05 01:30:48 +00:00
|
|
|
os << " // block is not in a region!";
|
2020-01-09 12:39:26 -08:00
|
|
|
} else if (block->hasNoPredecessors()) {
|
2022-01-19 12:18:30 -08:00
|
|
|
if (!block->isEntryBlock())
|
|
|
|
os << " // no predecessors";
|
2020-01-09 12:39:26 -08:00
|
|
|
} else if (auto *pred = block->getSinglePredecessor()) {
|
2020-05-05 01:30:48 +00:00
|
|
|
os << " // pred: ";
|
2020-01-09 12:39:26 -08:00
|
|
|
printBlockName(pred);
|
|
|
|
} else {
|
2022-02-07 21:10:18 +00:00
|
|
|
// We want to print the predecessors in a stable order, not in
|
2020-01-09 12:39:26 -08:00
|
|
|
// whatever order the use-list is in, so gather and sort them.
|
2022-02-07 21:10:18 +00:00
|
|
|
SmallVector<BlockInfo, 4> predIDs;
|
2020-01-09 12:39:26 -08:00
|
|
|
for (auto *pred : block->getPredecessors())
|
2022-09-02 21:23:47 -07:00
|
|
|
predIDs.push_back(state.getSSANameState().getBlockInfo(pred));
|
2022-02-07 21:10:18 +00:00
|
|
|
llvm::sort(predIDs, [](BlockInfo lhs, BlockInfo rhs) {
|
|
|
|
return lhs.ordering < rhs.ordering;
|
|
|
|
});
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2020-05-05 01:30:48 +00:00
|
|
|
os << " // " << predIDs.size() << " preds: ";
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2022-02-07 21:10:18 +00:00
|
|
|
interleaveComma(predIDs, [&](BlockInfo pred) { os << pred.name; });
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
2020-02-08 15:01:34 -08:00
|
|
|
os << newLine;
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
currentIndent += indentWidth;
|
2022-04-22 18:52:54 +00:00
|
|
|
|
|
|
|
if (printerFlags.shouldPrintValueUsers()) {
|
|
|
|
for (BlockArgument arg : block->getArguments()) {
|
|
|
|
os.indent(currentIndent);
|
|
|
|
printUsersComment(arg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-28 07:21:41 -04:00
|
|
|
bool hasTerminator =
|
|
|
|
!block->empty() && block->back().hasTrait<OpTrait::IsTerminator>();
|
2020-01-09 12:39:26 -08:00
|
|
|
auto range = llvm::make_range(
|
2021-05-28 07:21:41 -04:00
|
|
|
block->begin(),
|
|
|
|
std::prev(block->end(),
|
|
|
|
(!hasTerminator || printBlockTerminator) ? 0 : 1));
|
2020-01-09 12:39:26 -08:00
|
|
|
for (auto &op : range) {
|
2022-10-05 18:31:22 +00:00
|
|
|
printFullOpWithIndentAndLoc(&op);
|
2020-02-08 15:01:34 -08:00
|
|
|
os << newLine;
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
currentIndent -= indentWidth;
|
|
|
|
}
|
|
|
|
|
Add support for custom op parser/printer hooks to know about result names.
Summary:
This allows the custom parser/printer hooks to do interesting things with
the SSA names. This patch:
- Adds a new 'getResultName' method to OpAsmParser that allows a parser
implementation to get information about its result names, along with
a getNumResults() method that allows op parser impls to know how many
results are expected.
- Adds a OpAsmPrinter::printOperand overload that takes an explicit stream.
- Adds a test.string_attr_pretty_name operation that uses these hooks to
do fancy things with the result name.
Reviewers: rriddle!
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D76205
2020-03-15 17:13:59 -07:00
|
|
|
void OperationPrinter::printValueID(Value value, bool printResultNo,
|
|
|
|
raw_ostream *streamOverride) const {
|
2022-09-02 21:23:47 -07:00
|
|
|
state.getSSANameState().printValueID(value, printResultNo,
|
|
|
|
streamOverride ? *streamOverride : os);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
void OperationPrinter::printOperationID(Operation *op,
|
|
|
|
raw_ostream *streamOverride) const {
|
2022-09-02 21:23:47 -07:00
|
|
|
state.getSSANameState().printOperationID(op, streamOverride ? *streamOverride
|
|
|
|
: os);
|
2022-04-22 18:52:54 +00:00
|
|
|
}
|
|
|
|
|
2020-03-05 12:48:28 -08:00
|
|
|
void OperationPrinter::printSuccessor(Block *successor) {
|
|
|
|
printBlockName(successor);
|
|
|
|
}
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2020-03-05 12:48:28 -08:00
|
|
|
void OperationPrinter::printSuccessorAndUseList(Block *successor,
|
|
|
|
ValueRange succOperands) {
|
|
|
|
printBlockName(successor);
|
|
|
|
if (succOperands.empty())
|
2018-12-28 11:41:56 -08:00
|
|
|
return;
|
|
|
|
|
|
|
|
os << '(';
|
|
|
|
interleaveComma(succOperands,
|
2019-12-23 14:45:01 -08:00
|
|
|
[this](Value operand) { printValueID(operand); });
|
2018-12-28 11:41:56 -08:00
|
|
|
os << " : ";
|
2019-03-23 15:09:06 -07:00
|
|
|
interleaveComma(succOperands,
|
2020-01-11 08:54:04 -08:00
|
|
|
[this](Value operand) { printType(operand.getType()); });
|
2018-12-28 11:41:56 -08:00
|
|
|
os << ')';
|
2018-07-03 17:51:28 -07:00
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void OperationPrinter::printRegion(Region ®ion, bool printEntryBlockArgs,
|
2021-03-11 23:58:02 +00:00
|
|
|
bool printBlockTerminators,
|
|
|
|
bool printEmptyBlock) {
|
2023-03-13 14:33:31 +01:00
|
|
|
if (printerFlags.shouldSkipRegions()) {
|
|
|
|
os << "{...}";
|
|
|
|
return;
|
|
|
|
}
|
2022-01-18 07:47:25 +00:00
|
|
|
os << "{" << newLine;
|
2020-01-09 12:39:26 -08:00
|
|
|
if (!region.empty()) {
|
2021-08-28 03:03:49 +00:00
|
|
|
auto restoreDefaultDialect =
|
|
|
|
llvm::make_scope_exit([&]() { defaultDialectStack.pop_back(); });
|
|
|
|
if (auto iface = dyn_cast<OpAsmOpInterface>(region.getParentOp()))
|
|
|
|
defaultDialectStack.push_back(iface.getDefaultDialect());
|
|
|
|
else
|
|
|
|
defaultDialectStack.push_back("");
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
auto *entryBlock = ®ion.front();
|
2021-03-11 23:58:02 +00:00
|
|
|
// Force printing the block header if printEmptyBlock is set and the block
|
|
|
|
// is empty or if printEntryBlockArgs is set and there are arguments to
|
|
|
|
// print.
|
|
|
|
bool shouldAlwaysPrintBlockHeader =
|
|
|
|
(printEmptyBlock && entryBlock->empty()) ||
|
|
|
|
(printEntryBlockArgs && entryBlock->getNumArguments() != 0);
|
|
|
|
print(entryBlock, shouldAlwaysPrintBlockHeader, printBlockTerminators);
|
2020-01-09 12:39:26 -08:00
|
|
|
for (auto &b : llvm::drop_begin(region.getBlocks(), 1))
|
|
|
|
print(&b);
|
|
|
|
}
|
|
|
|
os.indent(currentIndent) << "}";
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printAffineMapOfSSAIds(AffineMapAttr mapAttr,
|
|
|
|
ValueRange operands) {
|
2023-02-26 10:46:01 -05:00
|
|
|
if (!mapAttr) {
|
|
|
|
os << "<<NULL AFFINE MAP>>";
|
|
|
|
return;
|
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
AffineMap map = mapAttr.getValue();
|
|
|
|
unsigned numDims = map.getNumDims();
|
|
|
|
auto printValueName = [&](unsigned pos, bool isSymbol) {
|
|
|
|
unsigned index = isSymbol ? numDims + pos : pos;
|
|
|
|
assert(index < operands.size());
|
|
|
|
if (isSymbol)
|
|
|
|
os << "symbol(";
|
|
|
|
printValueID(operands[index]);
|
|
|
|
if (isSymbol)
|
|
|
|
os << ')';
|
|
|
|
};
|
|
|
|
|
|
|
|
interleaveComma(map.getResults(), [&](AffineExpr expr) {
|
|
|
|
printAffineExpr(expr, printValueName);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-04-29 13:15:21 +02:00
|
|
|
void OperationPrinter::printAffineExprOfSSAIds(AffineExpr expr,
|
|
|
|
ValueRange dimOperands,
|
|
|
|
ValueRange symOperands) {
|
|
|
|
auto printValueName = [&](unsigned pos, bool isSymbol) {
|
|
|
|
if (!isSymbol)
|
|
|
|
return printValueID(dimOperands[pos]);
|
|
|
|
os << "symbol(";
|
|
|
|
printValueID(symOperands[pos]);
|
|
|
|
os << ')';
|
|
|
|
};
|
|
|
|
printAffineExpr(expr, printValueName);
|
|
|
|
}
|
|
|
|
|
2018-07-03 17:51:28 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// print and dump methods
|
|
|
|
//===----------------------------------------------------------------------===//
|
2018-06-28 20:45:33 -07:00
|
|
|
|
2022-09-13 17:35:38 -07:00
|
|
|
void Attribute::print(raw_ostream &os, bool elideType) const {
|
2022-09-02 21:23:47 -07:00
|
|
|
if (!*this) {
|
|
|
|
os << "<<NULL ATTRIBUTE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsmState state(getContext());
|
2022-09-13 17:35:38 -07:00
|
|
|
print(os, state, elideType);
|
2022-09-02 21:23:47 -07:00
|
|
|
}
|
2022-09-13 17:35:38 -07:00
|
|
|
void Attribute::print(raw_ostream &os, AsmState &state, bool elideType) const {
|
|
|
|
using AttrTypeElision = AsmPrinter::Impl::AttrTypeElision;
|
|
|
|
AsmPrinter::Impl(os, state.getImpl())
|
|
|
|
.printAttribute(*this, elideType ? AttrTypeElision::Must
|
|
|
|
: AttrTypeElision::Never);
|
2018-07-18 16:29:21 -07:00
|
|
|
}
|
|
|
|
|
2019-04-16 16:47:41 -07:00
|
|
|
void Attribute::dump() const {
|
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
2018-07-18 16:29:21 -07:00
|
|
|
|
2024-01-15 20:56:35 -08:00
|
|
|
void Attribute::printStripped(raw_ostream &os, AsmState &state) const {
|
|
|
|
if (!*this) {
|
|
|
|
os << "<<NULL ATTRIBUTE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsmPrinter::Impl subPrinter(os, state.getImpl());
|
|
|
|
if (succeeded(subPrinter.printAlias(*this)))
|
|
|
|
return;
|
|
|
|
|
|
|
|
auto &dialect = this->getDialect();
|
|
|
|
uint64_t posPrior = os.tell();
|
|
|
|
DialectAsmPrinter printer(subPrinter);
|
|
|
|
dialect.printAttribute(*this, printer);
|
|
|
|
if (posPrior != os.tell())
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Fallback to printing with prefix if the above failed to write anything
|
|
|
|
// to the output stream.
|
|
|
|
print(os, state);
|
|
|
|
}
|
|
|
|
void Attribute::printStripped(raw_ostream &os) const {
|
|
|
|
if (!*this) {
|
|
|
|
os << "<<NULL ATTRIBUTE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsmState state(getContext());
|
|
|
|
printStripped(os, state);
|
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void Type::print(raw_ostream &os) const {
|
2022-09-02 21:23:47 -07:00
|
|
|
if (!*this) {
|
|
|
|
os << "<<NULL TYPE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
AsmState state(getContext());
|
|
|
|
print(os, state);
|
|
|
|
}
|
|
|
|
void Type::print(raw_ostream &os, AsmState &state) const {
|
|
|
|
AsmPrinter::Impl(os, state.getImpl()).printType(*this);
|
2021-09-24 19:56:01 +00:00
|
|
|
}
|
2018-07-17 16:56:54 -07:00
|
|
|
|
2023-01-09 17:33:22 +00:00
|
|
|
void Type::dump() const {
|
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
2018-07-17 16:56:54 -07:00
|
|
|
|
2018-10-09 16:39:24 -07:00
|
|
|
void AffineMap::dump() const {
|
2018-07-16 09:45:22 -07:00
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
2018-07-09 09:00:25 -07:00
|
|
|
|
2018-10-10 09:45:59 -07:00
|
|
|
void IntegerSet::dump() const {
|
2018-08-07 14:24:38 -07:00
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
|
|
|
|
2018-10-09 10:59:27 -07:00
|
|
|
void AffineExpr::print(raw_ostream &os) const {
|
2020-04-06 00:43:07 +05:30
|
|
|
if (!expr) {
|
|
|
|
os << "<<NULL AFFINE EXPR>>";
|
2019-01-07 17:34:26 -08:00
|
|
|
return;
|
|
|
|
}
|
2022-09-02 21:23:47 -07:00
|
|
|
AsmState state(getContext());
|
|
|
|
AsmPrinter::Impl(os, state.getImpl()).printAffineExpr(*this);
|
2018-10-09 10:59:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
void AffineExpr::dump() const {
|
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
2018-06-29 18:09:29 -07:00
|
|
|
}
|
|
|
|
|
2018-10-09 16:39:24 -07:00
|
|
|
void AffineMap::print(raw_ostream &os) const {
|
2020-04-06 00:43:07 +05:30
|
|
|
if (!map) {
|
|
|
|
os << "<<NULL AFFINE MAP>>";
|
2019-01-07 17:34:26 -08:00
|
|
|
return;
|
|
|
|
}
|
2022-09-02 21:23:47 -07:00
|
|
|
AsmState state(getContext());
|
|
|
|
AsmPrinter::Impl(os, state.getImpl()).printAffineMap(*this);
|
2018-07-20 09:35:47 -07:00
|
|
|
}
|
2018-07-11 21:31:07 -07:00
|
|
|
|
2018-10-10 09:45:59 -07:00
|
|
|
void IntegerSet::print(raw_ostream &os) const {
|
2022-09-02 21:23:47 -07:00
|
|
|
AsmState state(getContext());
|
|
|
|
AsmPrinter::Impl(os, state.getImpl()).printIntegerSet(*this);
|
2018-08-07 14:24:38 -07:00
|
|
|
}
|
|
|
|
|
2023-11-21 12:52:15 +08:00
|
|
|
void Value::print(raw_ostream &os) const { print(os, OpPrintingFlags()); }
|
|
|
|
void Value::print(raw_ostream &os, const OpPrintingFlags &flags) const {
|
2022-01-04 08:12:51 +05:30
|
|
|
if (!impl) {
|
|
|
|
os << "<<NULL VALUE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-10-14 16:21:17 -07:00
|
|
|
if (auto *op = getDefiningOp())
|
2022-03-07 07:49:46 -08:00
|
|
|
return op->print(os, flags);
|
2021-05-23 14:08:31 -07:00
|
|
|
// TODO: Improve BlockArgument print'ing.
|
2023-05-26 10:17:47 +02:00
|
|
|
BlockArgument arg = llvm::cast<BlockArgument>(*this);
|
2020-09-15 10:58:45 +05:30
|
|
|
os << "<block argument> of type '" << arg.getType()
|
2021-06-16 11:10:00 +00:00
|
|
|
<< "' at index: " << arg.getArgNumber();
|
2018-08-02 17:16:58 -07:00
|
|
|
}
|
2023-11-21 12:52:15 +08:00
|
|
|
void Value::print(raw_ostream &os, AsmState &state) const {
|
2022-01-04 08:12:51 +05:30
|
|
|
if (!impl) {
|
|
|
|
os << "<<NULL VALUE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-01-14 15:23:05 -08:00
|
|
|
if (auto *op = getDefiningOp())
|
|
|
|
return op->print(os, state);
|
|
|
|
|
2021-05-23 14:08:31 -07:00
|
|
|
// TODO: Improve BlockArgument print'ing.
|
2023-05-26 10:17:47 +02:00
|
|
|
BlockArgument arg = llvm::cast<BlockArgument>(*this);
|
2020-09-15 10:58:45 +05:30
|
|
|
os << "<block argument> of type '" << arg.getType()
|
2021-06-16 11:10:00 +00:00
|
|
|
<< "' at index: " << arg.getArgNumber();
|
2020-01-14 15:23:05 -08:00
|
|
|
}
|
2018-08-02 17:16:58 -07:00
|
|
|
|
2023-11-21 12:52:15 +08:00
|
|
|
void Value::dump() const {
|
2019-09-27 16:20:04 -07:00
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
2018-08-02 17:16:58 -07:00
|
|
|
|
2023-11-21 12:52:15 +08:00
|
|
|
void Value::printAsOperand(raw_ostream &os, AsmState &state) const {
|
2020-07-07 01:35:23 -07:00
|
|
|
// TODO: This doesn't necessarily capture all potential cases.
|
2020-01-14 15:23:05 -08:00
|
|
|
// Currently, region arguments can be shadowed when printing the main
|
|
|
|
// operation. If the IR hasn't been printed, this will produce the old SSA
|
|
|
|
// name and not the shadowed name.
|
|
|
|
state.getImpl().getSSANameState().printValueID(*this, /*printResultNo=*/true,
|
|
|
|
os);
|
|
|
|
}
|
|
|
|
|
2023-05-07 18:19:46 -05:00
|
|
|
static Operation *findParent(Operation *op, bool shouldUseLocalScope) {
|
2020-04-06 11:04:22 -07:00
|
|
|
do {
|
|
|
|
// If we are printing local scope, stop at the first operation that is
|
|
|
|
// isolated from above.
|
2021-02-09 11:41:10 -08:00
|
|
|
if (shouldUseLocalScope && op->hasTrait<OpTrait::IsIsolatedFromAbove>())
|
2020-04-06 11:04:22 -07:00
|
|
|
break;
|
2019-07-03 13:21:24 -07:00
|
|
|
|
2020-04-06 11:04:22 -07:00
|
|
|
// Otherwise, traverse up to the next parent.
|
2021-02-09 11:41:10 -08:00
|
|
|
Operation *parentOp = op->getParentOp();
|
2020-04-06 11:04:22 -07:00
|
|
|
if (!parentOp)
|
|
|
|
break;
|
2021-02-09 11:41:10 -08:00
|
|
|
op = parentOp;
|
2020-04-06 11:04:22 -07:00
|
|
|
} while (true);
|
2023-05-07 18:19:46 -05:00
|
|
|
return op;
|
|
|
|
}
|
2018-12-28 11:41:56 -08:00
|
|
|
|
2023-11-21 12:52:15 +08:00
|
|
|
void Value::printAsOperand(raw_ostream &os,
|
|
|
|
const OpPrintingFlags &flags) const {
|
2023-05-07 18:19:46 -05:00
|
|
|
Operation *op;
|
2023-05-26 10:17:47 +02:00
|
|
|
if (auto result = llvm::dyn_cast<OpResult>(*this)) {
|
2023-05-07 18:19:46 -05:00
|
|
|
op = result.getOwner();
|
|
|
|
} else {
|
2023-05-26 10:17:47 +02:00
|
|
|
op = llvm::cast<BlockArgument>(*this).getOwner()->getParentOp();
|
2023-05-07 18:19:46 -05:00
|
|
|
if (!op) {
|
|
|
|
os << "<<UNKNOWN SSA VALUE>>";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
op = findParent(op, flags.shouldUseLocalScope());
|
|
|
|
AsmState state(op, flags);
|
|
|
|
printAsOperand(os, state);
|
|
|
|
}
|
|
|
|
|
|
|
|
void Operation::print(raw_ostream &os, const OpPrintingFlags &printerFlags) {
|
|
|
|
// Find the operation to number from based upon the provided flags.
|
|
|
|
Operation *op = findParent(this, printerFlags.shouldUseLocalScope());
|
2021-07-10 16:39:44 +00:00
|
|
|
AsmState state(op, printerFlags);
|
2022-02-15 17:09:08 -08:00
|
|
|
print(os, state);
|
2020-01-14 15:23:05 -08:00
|
|
|
}
|
2022-02-15 17:09:08 -08:00
|
|
|
void Operation::print(raw_ostream &os, AsmState &state) {
|
|
|
|
OperationPrinter printer(os, state.getImpl());
|
2022-09-13 01:07:29 -07:00
|
|
|
if (!getParent() && !state.getPrinterFlags().shouldUseLocalScope()) {
|
|
|
|
state.getImpl().initializeAliases(this);
|
2020-12-03 15:46:23 -08:00
|
|
|
printer.printTopLevelOperation(this);
|
2022-09-13 01:07:29 -07:00
|
|
|
} else {
|
2022-10-05 18:31:22 +00:00
|
|
|
printer.printFullOpWithIndentAndLoc(this);
|
2022-09-13 01:07:29 -07:00
|
|
|
}
|
2018-07-20 09:35:47 -07:00
|
|
|
}
|
2018-07-11 21:31:07 -07:00
|
|
|
|
2019-03-26 17:05:09 -07:00
|
|
|
void Operation::dump() {
|
2019-11-12 09:36:40 -08:00
|
|
|
print(llvm::errs(), OpPrintingFlags().useLocalScope());
|
2018-07-20 09:35:47 -07:00
|
|
|
llvm::errs() << "\n";
|
2018-06-29 18:09:29 -07:00
|
|
|
}
|
|
|
|
|
2024-12-17 23:44:36 -05:00
|
|
|
void Operation::dumpPretty() {
|
|
|
|
print(llvm::errs(), OpPrintingFlags().useLocalScope().assumeVerified());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
|
|
|
|
2019-03-21 17:53:00 -07:00
|
|
|
void Block::print(raw_ostream &os) {
|
2020-01-09 12:39:26 -08:00
|
|
|
Operation *parentOp = getParentOp();
|
|
|
|
if (!parentOp) {
|
2018-08-03 11:12:34 -07:00
|
|
|
os << "<<UNLINKED BLOCK>>\n";
|
|
|
|
return;
|
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
// Get the top-level op.
|
|
|
|
while (auto *nextOp = parentOp->getParentOp())
|
|
|
|
parentOp = nextOp;
|
2018-12-27 11:07:34 -08:00
|
|
|
|
2020-01-14 15:23:05 -08:00
|
|
|
AsmState state(parentOp);
|
|
|
|
print(os, state);
|
|
|
|
}
|
|
|
|
void Block::print(raw_ostream &os, AsmState &state) {
|
2022-02-15 17:09:08 -08:00
|
|
|
OperationPrinter(os, state.getImpl()).print(this);
|
2018-06-23 16:03:42 -07:00
|
|
|
}
|
|
|
|
|
2019-03-21 17:53:00 -07:00
|
|
|
void Block::dump() { print(llvm::errs()); }
|
2018-06-23 16:03:42 -07:00
|
|
|
|
2018-12-28 21:24:30 -08:00
|
|
|
/// Print out the name of the block without printing its body.
|
2018-12-28 13:07:39 -08:00
|
|
|
void Block::printAsOperand(raw_ostream &os, bool printType) {
|
2020-01-09 12:39:26 -08:00
|
|
|
Operation *parentOp = getParentOp();
|
|
|
|
if (!parentOp) {
|
2018-09-21 14:40:36 -07:00
|
|
|
os << "<<UNLINKED BLOCK>>\n";
|
|
|
|
return;
|
|
|
|
}
|
2020-01-14 15:23:05 -08:00
|
|
|
AsmState state(parentOp);
|
|
|
|
printAsOperand(os, state);
|
|
|
|
}
|
|
|
|
void Block::printAsOperand(raw_ostream &os, AsmState &state) {
|
2022-02-15 17:09:08 -08:00
|
|
|
OperationPrinter printer(os, state.getImpl());
|
2020-01-14 15:23:05 -08:00
|
|
|
printer.printBlockName(this);
|
2019-07-03 13:21:24 -07:00
|
|
|
}
|
2023-12-08 11:34:44 -08:00
|
|
|
|
2024-05-18 08:03:19 -05:00
|
|
|
raw_ostream &mlir::operator<<(raw_ostream &os, Block &block) {
|
|
|
|
block.print(os);
|
|
|
|
return os;
|
|
|
|
}
|
|
|
|
|
2023-12-08 11:34:44 -08:00
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
// Custom printers
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
namespace mlir {
|
|
|
|
|
|
|
|
void printDimensionList(OpAsmPrinter &printer, Operation *op,
|
|
|
|
ArrayRef<int64_t> dimensions) {
|
|
|
|
if (dimensions.empty())
|
|
|
|
printer << "[";
|
|
|
|
printer.printDimensionList(dimensions);
|
|
|
|
if (dimensions.empty())
|
|
|
|
printer << "]";
|
|
|
|
}
|
|
|
|
|
|
|
|
ParseResult parseDimensionList(OpAsmParser &parser,
|
|
|
|
DenseI64ArrayAttr &dimensions) {
|
|
|
|
// Empty list case denoted by "[]".
|
|
|
|
if (succeeded(parser.parseOptionalLSquare())) {
|
|
|
|
if (failed(parser.parseRSquare())) {
|
|
|
|
return parser.emitError(parser.getCurrentLocation())
|
|
|
|
<< "Failed parsing dimension list.";
|
|
|
|
}
|
|
|
|
dimensions =
|
|
|
|
DenseI64ArrayAttr::get(parser.getContext(), ArrayRef<int64_t>());
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Non-empty list case.
|
|
|
|
SmallVector<int64_t> shapeArr;
|
|
|
|
if (failed(parser.parseDimensionList(shapeArr, true, false))) {
|
|
|
|
return parser.emitError(parser.getCurrentLocation())
|
|
|
|
<< "Failed parsing dimension list.";
|
|
|
|
}
|
|
|
|
if (shapeArr.empty()) {
|
|
|
|
return parser.emitError(parser.getCurrentLocation())
|
|
|
|
<< "Failed parsing dimension list. Did you mean an empty list? It "
|
|
|
|
"must be denoted by \"[]\".";
|
|
|
|
}
|
|
|
|
dimensions = DenseI64ArrayAttr::get(parser.getContext(), shapeArr);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace mlir
|