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"
|
2021-11-02 05:51:38 +00:00
|
|
|
#include "mlir/IR/BuiltinDialect.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"
|
2021-06-10 17:22:49 -07:00
|
|
|
#include "mlir/IR/SubElementInterfaces.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"
|
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"
|
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"
|
2021-05-12 11:21:25 +08:00
|
|
|
|
|
|
|
#include <tuple>
|
|
|
|
|
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(); }
|
|
|
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
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() &&
|
|
|
|
op->getResult(0).getType().isa<FunctionType>())
|
|
|
|
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.
|
|
|
|
#include "mlir/IR/OpAsmInterface.cpp.inc"
|
|
|
|
|
[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")};
|
|
|
|
|
|
|
|
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 "
|
|
|
|
"aliases for attributes, types, and locations")};
|
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")};
|
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),
|
2022-03-07 07:49:46 -08:00
|
|
|
printGenericOpFormFlag(false), assumeVerifiedFlag(false),
|
2022-04-22 18:52:54 +00:00
|
|
|
printLocalScope(false), printValueUsersFlag(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;
|
|
|
|
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;
|
2022-04-22 18:52:54 +00:00
|
|
|
printValueUsersFlag = clOptions->printValueUsers;
|
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;
|
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
OpPrintingFlags &OpPrintingFlags::enableDebugInfo(bool prettyForm) {
|
|
|
|
printDebugInfoFlag = true;
|
|
|
|
printDebugInfoPrettyFormFlag = prettyForm;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Always print operations in the generic form.
|
|
|
|
OpPrintingFlags &OpPrintingFlags::printGenericOpForm() {
|
|
|
|
printGenericOpFormFlag = true;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
/// Do not verify the operation when using custom operation printers.
|
|
|
|
OpPrintingFlags &OpPrintingFlags::assumeVerified() {
|
|
|
|
assumeVerifiedFlag = true;
|
|
|
|
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.
|
|
|
|
OpPrintingFlags &OpPrintingFlags::useLocalScope() {
|
|
|
|
printLocalScope = true;
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2022-04-22 18:52:54 +00:00
|
|
|
/// Print users of values as comments.
|
|
|
|
OpPrintingFlags &OpPrintingFlags::printValueUsers() {
|
|
|
|
printValueUsersFlag = true;
|
|
|
|
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()) &&
|
|
|
|
!attr.isa<SplatElementsAttr>();
|
2019-10-07 17:18:54 -07:00
|
|
|
}
|
|
|
|
|
2020-04-08 12:57:02 -07:00
|
|
|
/// Return the size limit for printing large ElementsAttr.
|
|
|
|
Optional<int64_t> OpPrintingFlags::getLargeElementsAttrLimit() const {
|
|
|
|
return elementsAttrElementLimit;
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2020-04-11 23:11:51 -07:00
|
|
|
/// Returns true if an ElementsAttr with the given number of elements should be
|
|
|
|
/// printed with hex.
|
|
|
|
static bool shouldPrintElementsAttrWithHex(int64_t numElements) {
|
|
|
|
// Check to see if a command line option was provided for the limit.
|
|
|
|
if (clOptions.isConstructed()) {
|
|
|
|
if (clOptions->printElementsAttrWithHexIfLarger.getNumOccurrences()) {
|
|
|
|
// -1 is used to disable hex printing.
|
|
|
|
if (clOptions->printElementsAttrWithHexIfLarger == -1)
|
|
|
|
return false;
|
|
|
|
return numElements > clOptions->printElementsAttrWithHexIfLarger;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, default to printing with hex if the number of elements is >100.
|
|
|
|
return numElements > 100;
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
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:
|
|
|
|
SymbolAlias(StringRef name, bool isDeferrable)
|
|
|
|
: name(name), suffixIndex(0), hasSuffixIndex(false),
|
|
|
|
isDeferrable(isDeferrable) {}
|
|
|
|
SymbolAlias(StringRef name, uint32_t suffixIndex, bool isDeferrable)
|
|
|
|
: name(name), suffixIndex(suffixIndex), hasSuffixIndex(true),
|
|
|
|
isDeferrable(isDeferrable) {}
|
|
|
|
|
|
|
|
/// Print this alias to the given stream.
|
|
|
|
void print(raw_ostream &os) const {
|
|
|
|
os << name;
|
|
|
|
if (hasSuffixIndex)
|
|
|
|
os << suffixIndex;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns true if this alias supports deferred resolution when parsing.
|
|
|
|
bool canBeDeferred() const { return isDeferrable; }
|
|
|
|
|
|
|
|
private:
|
|
|
|
/// The main name of the alias.
|
|
|
|
StringRef name;
|
|
|
|
/// The optional suffix index of the alias, if multiple aliases had the same
|
|
|
|
/// name.
|
|
|
|
uint32_t suffixIndex : 30;
|
|
|
|
/// A flag indicating whether this alias has a suffix or not.
|
|
|
|
bool hasSuffixIndex : 1;
|
|
|
|
/// A flag indicating whether this alias may be deferred or not.
|
|
|
|
bool isDeferrable : 1;
|
|
|
|
};
|
|
|
|
|
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,
|
|
|
|
llvm::MapVector<Attribute, SymbolAlias> &attrToAlias,
|
|
|
|
llvm::MapVector<Type, SymbolAlias> &typeToAlias);
|
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).
|
|
|
|
void visit(Attribute attr, bool canBeDeferred = false);
|
2018-07-20 09:35:47 -07:00
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// Visit the given type to see if it has an alias.
|
|
|
|
void visit(Type type);
|
2019-08-21 16:50:30 -07:00
|
|
|
|
2019-05-06 10:36:32 -07:00
|
|
|
private:
|
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.
|
2020-11-12 23:33:43 -08:00
|
|
|
/// Returns success if an alias was generated, failure otherwise.
|
2020-11-09 21:50:31 -08:00
|
|
|
template <typename T>
|
2020-11-12 23:33:43 -08:00
|
|
|
LogicalResult
|
|
|
|
generateAlias(T symbol,
|
|
|
|
llvm::MapVector<StringRef, std::vector<T>> &aliasToSymbol);
|
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;
|
|
|
|
|
|
|
|
/// Mapping between an alias and the set of symbols mapped to it.
|
|
|
|
llvm::MapVector<StringRef, std::vector<Attribute>> aliasToAttr;
|
|
|
|
llvm::MapVector<StringRef, std::vector<Type>> aliasToType;
|
2019-05-06 10:36:32 -07:00
|
|
|
|
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;
|
|
|
|
|
|
|
|
/// The set of visited attributes.
|
|
|
|
DenseSet<Attribute> visitedAttributes;
|
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
/// The set of attributes that have aliases *and* can be deferred.
|
|
|
|
DenseSet<Attribute> deferrableAttributes;
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
/// The set of visited types.
|
|
|
|
DenseSet<Type> visitedTypes;
|
|
|
|
|
|
|
|
/// 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
|
|
|
|
|
|
|
/// Print the given operation.
|
|
|
|
void print(Operation *op) {
|
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()) {
|
|
|
|
// Check to see if this is a known operation. If so, use the registered
|
|
|
|
// custom printer hook.
|
2021-11-17 21:50:28 +00:00
|
|
|
if (auto opInfo = op->getRegisteredInfo()) {
|
2021-08-28 03:03:49 +00:00
|
|
|
opInfo->printAssembly(op, *this, /*defaultDialect=*/"");
|
2020-11-09 21:50:31 -08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2020-11-09 21:50:31 -08:00
|
|
|
if (op->getNumRegions() != 0) {
|
|
|
|
for (Region ®ion : op->getRegions())
|
|
|
|
printRegion(region, /*printEntryBlockArgs=*/true,
|
|
|
|
/*printBlockTerminators=*/true);
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
print(&op);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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;
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
/// 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.
|
2021-09-24 19:56:01 +00:00
|
|
|
void printFloat(const APFloat &value) 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 {}
|
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 {}
|
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
|
|
|
};
|
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,
|
|
|
|
StringRef allowedPunctChars = "$._-",
|
|
|
|
bool allowTrailingDigit = true) {
|
|
|
|
assert(!name.empty() && "Shouldn't have an empty name here");
|
2019-01-10 22:08:39 -08:00
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
auto copyNameToBuffer = [&] {
|
|
|
|
for (char ch : name) {
|
|
|
|
if (llvm::isAlnum(ch) || allowedPunctChars.contains(ch))
|
|
|
|
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.
|
|
|
|
if (isdigit(name[0])) {
|
|
|
|
buffer.push_back('_');
|
|
|
|
copyNameToBuffer();
|
|
|
|
return buffer;
|
2019-01-10 22:08:39 -08:00
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// If the name ends with a trailing digit, add a '_' to avoid potential
|
|
|
|
// conflicts with autogenerated ID's.
|
|
|
|
if (!allowTrailingDigit && isdigit(name.back())) {
|
|
|
|
copyNameToBuffer();
|
|
|
|
buffer.push_back('_');
|
|
|
|
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) {
|
|
|
|
if (!llvm::isAlnum(ch) && !allowedPunctChars.contains(ch)) {
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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.
|
|
|
|
template <typename T>
|
2020-11-12 23:33:43 -08:00
|
|
|
static void
|
|
|
|
initializeAliases(llvm::MapVector<StringRef, std::vector<T>> &aliasToSymbol,
|
|
|
|
llvm::MapVector<T, SymbolAlias> &symbolToAlias,
|
|
|
|
DenseSet<T> *deferrableAliases = nullptr) {
|
2020-10-30 00:30:59 -07:00
|
|
|
std::vector<std::pair<StringRef, std::vector<T>>> aliases =
|
|
|
|
aliasToSymbol.takeVector();
|
|
|
|
llvm::array_pod_sort(aliases.begin(), aliases.end(),
|
|
|
|
[](const auto *lhs, const auto *rhs) {
|
|
|
|
return lhs->first.compare(rhs->first);
|
|
|
|
});
|
|
|
|
|
|
|
|
for (auto &it : aliases) {
|
|
|
|
// If there is only one instance for this alias, use the name directly.
|
|
|
|
if (it.second.size() == 1) {
|
2020-11-12 23:33:43 -08:00
|
|
|
T symbol = it.second.front();
|
|
|
|
bool isDeferrable = deferrableAliases && deferrableAliases->count(symbol);
|
|
|
|
symbolToAlias.insert({symbol, SymbolAlias(it.first, isDeferrable)});
|
2020-10-30 00:30:59 -07:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// Otherwise, add the index to the name.
|
2020-11-12 23:33:43 -08:00
|
|
|
for (int i = 0, e = it.second.size(); i < e; ++i) {
|
|
|
|
T symbol = it.second[i];
|
|
|
|
bool isDeferrable = deferrableAliases && deferrableAliases->count(symbol);
|
|
|
|
symbolToAlias.insert({symbol, SymbolAlias(it.first, i, isDeferrable)});
|
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
void AliasInitializer::initialize(
|
|
|
|
Operation *op, const OpPrintingFlags &printerFlags,
|
2020-11-12 23:33:43 -08:00
|
|
|
llvm::MapVector<Attribute, SymbolAlias> &attrToAlias,
|
|
|
|
llvm::MapVector<Type, SymbolAlias> &typeToAlias) {
|
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);
|
|
|
|
aliasPrinter.print(op);
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
// Initialize the aliases sorted by name.
|
2020-11-12 23:33:43 -08:00
|
|
|
initializeAliases(aliasToAttr, attrToAlias, &deferrableAttributes);
|
2020-10-30 00:30:59 -07:00
|
|
|
initializeAliases(aliasToType, typeToAlias);
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
void AliasInitializer::visit(Attribute attr, bool canBeDeferred) {
|
|
|
|
if (!visitedAttributes.insert(attr).second) {
|
|
|
|
// If this attribute already has an alias and this instance can't be
|
|
|
|
// deferred, make sure that the alias isn't deferred.
|
|
|
|
if (!canBeDeferred)
|
|
|
|
deferrableAttributes.erase(attr);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to generate an alias for this attribute.
|
|
|
|
if (succeeded(generateAlias(attr, aliasToAttr))) {
|
|
|
|
if (canBeDeferred)
|
|
|
|
deferrableAttributes.insert(attr);
|
2020-01-08 10:11:56 -08:00
|
|
|
return;
|
2020-11-12 23:33:43 -08:00
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2021-06-10 17:22:49 -07:00
|
|
|
// Check for any sub elements.
|
|
|
|
if (auto subElementInterface = attr.dyn_cast<SubElementAttrInterface>()) {
|
|
|
|
subElementInterface.walkSubElements([&](Attribute attr) { visit(attr); },
|
|
|
|
[&](Type type) { visit(type); });
|
2020-10-30 00:30:59 -07:00
|
|
|
}
|
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2020-11-09 21:50:31 -08:00
|
|
|
void AliasInitializer::visit(Type type) {
|
2020-10-30 00:30:59 -07:00
|
|
|
if (!visitedTypes.insert(type).second)
|
|
|
|
return;
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
// Try to generate an alias for this type.
|
|
|
|
if (succeeded(generateAlias(type, aliasToType)))
|
|
|
|
return;
|
|
|
|
|
2021-06-10 17:22:49 -07:00
|
|
|
// Check for any sub elements.
|
|
|
|
if (auto subElementInterface = type.dyn_cast<SubElementTypeInterface>()) {
|
|
|
|
subElementInterface.walkSubElements([&](Attribute attr) { visit(attr); },
|
|
|
|
[&](Type type) { visit(type); });
|
2020-01-08 10:11:56 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-30 00:30:59 -07:00
|
|
|
template <typename T>
|
2020-11-12 23:33:43 -08:00
|
|
|
LogicalResult AliasInitializer::generateAlias(
|
2020-10-30 00:30:59 -07:00
|
|
|
T symbol, llvm::MapVector<StringRef, std::vector<T>> &aliasToSymbol) {
|
2021-08-03 17:23:31 +03:00
|
|
|
SmallString<32> nameBuffer;
|
2020-10-30 00:30:59 -07:00
|
|
|
for (const auto &interface : interfaces) {
|
2021-08-03 17:23:31 +03:00
|
|
|
OpAsmDialectInterface::AliasResult result =
|
|
|
|
interface.getAlias(symbol, aliasOS);
|
|
|
|
if (result == OpAsmDialectInterface::AliasResult::NoAlias)
|
2020-10-30 00:30:59 -07:00
|
|
|
continue;
|
2021-08-03 17:23:31 +03:00
|
|
|
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())
|
|
|
|
return failure();
|
|
|
|
|
|
|
|
SmallString<16> tempBuffer;
|
|
|
|
StringRef name =
|
|
|
|
sanitizeIdentifier(nameBuffer, tempBuffer, /*allowedPunctChars=*/"$_-",
|
|
|
|
/*allowTrailingDigit=*/false);
|
|
|
|
name = name.copy(aliasAllocator);
|
|
|
|
aliasToSymbol[name].push_back(symbol);
|
|
|
|
return success();
|
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.
|
|
|
|
void printNonDeferredAliases(raw_ostream &os, NewLineCounter &newLine) const {
|
|
|
|
printAliases(os, newLine, /*isDeferred=*/false);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Print all of the referenced aliases that support deferred resolution.
|
|
|
|
void printDeferredAliases(raw_ostream &os, NewLineCounter &newLine) const {
|
|
|
|
printAliases(os, newLine, /*isDeferred=*/true);
|
|
|
|
}
|
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.
|
|
|
|
void printAliases(raw_ostream &os, NewLineCounter &newLine,
|
|
|
|
bool isDeferred) const;
|
|
|
|
|
|
|
|
/// Mapping between attribute and alias.
|
|
|
|
llvm::MapVector<Attribute, SymbolAlias> attrToAlias;
|
|
|
|
/// Mapping between type and alias.
|
|
|
|
llvm::MapVector<Type, SymbolAlias> typeToAlias;
|
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);
|
2020-11-09 21:50:31 -08:00
|
|
|
initializer.initialize(op, printerFlags, attrToAlias, typeToAlias);
|
2020-10-30 00:30:59 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult AliasState::getAlias(Attribute attr, raw_ostream &os) const {
|
|
|
|
auto it = attrToAlias.find(attr);
|
|
|
|
if (it == attrToAlias.end())
|
|
|
|
return failure();
|
2020-11-12 23:33:43 -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 {
|
|
|
|
auto it = typeToAlias.find(ty);
|
|
|
|
if (it == typeToAlias.end())
|
|
|
|
return failure();
|
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
it->second.print(os << '!');
|
2020-10-30 00:30:59 -07:00
|
|
|
return success();
|
|
|
|
}
|
2020-01-08 10:11:56 -08:00
|
|
|
|
2020-11-12 23:33:43 -08:00
|
|
|
void AliasState::printAliases(raw_ostream &os, NewLineCounter &newLine,
|
|
|
|
bool isDeferred) const {
|
|
|
|
auto filterFn = [=](const auto &aliasIt) {
|
|
|
|
return aliasIt.second.canBeDeferred() == isDeferred;
|
|
|
|
};
|
|
|
|
for (const auto &it : llvm::make_filter_range(attrToAlias, filterFn)) {
|
|
|
|
it.second.print(os << '#');
|
|
|
|
os << " = " << it.first << newLine;
|
|
|
|
}
|
|
|
|
for (const auto &it : llvm::make_filter_range(typeToAlias, filterFn)) {
|
|
|
|
it.second.print(os << '!');
|
2022-05-12 13:36:05 -07:00
|
|
|
os << " = " << it.first << 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);
|
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,
|
|
|
|
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) {
|
2021-05-12 11:21:25 +08:00
|
|
|
llvm::SaveAndRestore<unsigned> valueIDSaver(nextValueID);
|
|
|
|
llvm::SaveAndRestore<unsigned> argumentIDSaver(nextArgumentID);
|
|
|
|
llvm::SaveAndRestore<unsigned> conflictIDSaver(nextConflictID);
|
|
|
|
|
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;
|
2021-05-12 11:21:25 +08:00
|
|
|
std::tie(region, nextValueID, nextArgumentID, nextConflictID, parentScope) =
|
|
|
|
nameContext.pop_back_val();
|
|
|
|
|
|
|
|
// 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
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
Optional<int> resultNo;
|
|
|
|
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.
|
|
|
|
if (OpResult result = value.dyn_cast<OpResult>())
|
|
|
|
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)
|
2020-01-09 12:39:26 -08: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()) {
|
|
|
|
stream << "<<UNKOWN OPERATION>>";
|
|
|
|
} 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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-10 16:39:34 +00:00
|
|
|
void SSANameState::numberValuesInRegion(Region ®ion) {
|
2021-12-20 07:17:26 +00:00
|
|
|
auto setBlockArgNameFn = [&](Value arg, StringRef name) {
|
|
|
|
assert(!valueIDs.count(arg) && "arg numbered multiple times");
|
|
|
|
assert(arg.cast<BlockArgument>().getOwner()->getParent() == ®ion &&
|
|
|
|
"arg not defined in current region");
|
|
|
|
setValueName(arg, name);
|
|
|
|
};
|
|
|
|
|
|
|
|
if (!printerFlags.shouldPrintGenericOpForm()) {
|
|
|
|
if (Operation *op = region.getParentOp()) {
|
|
|
|
if (auto asmInterface = dyn_cast<OpAsmOpInterface>(op))
|
|
|
|
asmInterface.getAsmBlockArgumentNames(region, setBlockArgNameFn);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
2020-01-09 12:39:26 -08:00
|
|
|
setValueName(arg, specialName.str());
|
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);
|
|
|
|
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'");
|
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.
|
2020-01-11 08:54:04 -08:00
|
|
|
if (int resultNo = result.cast<OpResult>().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
|
|
|
}
|
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);
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
void SSANameState::getResultIDAndNumber(OpResult result, Value &lookupValue,
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
[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;
|
|
|
|
|
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) {}
|
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; }
|
|
|
|
|
[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);
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
|
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
|
|
|
|
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
|
|
|
|
|
|
|
// Allow direct access to the impl fields.
|
|
|
|
friend AsmState;
|
2020-01-09 12:39:26 -08:00
|
|
|
};
|
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;
|
|
|
|
|
2022-05-10 22:48:46 +00:00
|
|
|
LLVM_DEBUG(llvm::dbgs() << DEBUG_TYPE << ": Verifying operation: "
|
|
|
|
<< op->getName() << "\n");
|
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
// 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,
|
|
|
|
LocationMap *locationMap)
|
2022-03-07 07:49:46 -08:00
|
|
|
: impl(std::make_unique<AsmStateImpl>(
|
|
|
|
op, verifyOpAndAdjustFlags(op, printerFlags), locationMap)) {}
|
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));
|
|
|
|
}
|
|
|
|
|
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
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
namespace mlir {
|
|
|
|
class AsmPrinter::Impl {
|
2020-01-09 12:39:26 -08:00
|
|
|
public:
|
2021-09-24 19:56:01 +00:00
|
|
|
Impl(raw_ostream &os, OpPrintingFlags flags = llvm::None,
|
|
|
|
AsmStateImpl *state = nullptr)
|
2020-01-09 12:39:26 -08:00
|
|
|
: os(os), printerFlags(flags), state(state) {}
|
2021-09-24 19:56:01 +00:00
|
|
|
explicit Impl(Impl &other)
|
|
|
|
: Impl(other.os, other.printerFlags, other.state) {}
|
2020-01-09 12:39:26 -08:00
|
|
|
|
|
|
|
/// Returns the output stream of the printer.
|
|
|
|
raw_ostream &getStream() { return os; }
|
|
|
|
|
|
|
|
template <typename Container, typename UnaryFunctor>
|
2021-12-20 19:45:05 +00:00
|
|
|
inline void interleaveComma(const Container &c, UnaryFunctor eachFn) const {
|
|
|
|
llvm::interleaveComma(c, os, eachFn);
|
2020-01-09 12:39:26 -08: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
|
|
|
/// This enum describes the different kinds of elision for the type of an
|
2020-02-08 10:01:17 -08:00
|
|
|
/// 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.
|
|
|
|
void printAttribute(Attribute attr,
|
|
|
|
AttrTypeElision typeElision = AttrTypeElision::Never);
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2021-12-08 01:24:51 +00:00
|
|
|
/// Print the alias for the given attribute, return failure if no alias could
|
|
|
|
/// be printed.
|
|
|
|
LogicalResult printAlias(Attribute attr);
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void printType(Type type);
|
2020-11-09 21:50:47 -08:00
|
|
|
|
2021-12-08 01:24:51 +00:00
|
|
|
/// Print the alias for the given type, return failure if no alias could
|
|
|
|
/// be printed.
|
|
|
|
LogicalResult printAlias(Type type);
|
|
|
|
|
2020-11-09 21:50:47 -08:00
|
|
|
/// 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);
|
2020-01-09 12:39:26 -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
|
|
|
/// Print a reference to the given resource that is owned by the given
|
|
|
|
/// dialect.
|
|
|
|
void printResourceHandle(const AsmDialectResourceHandle &resource) {
|
|
|
|
auto *interface = cast<OpAsmDialectInterface>(resource.getDialect());
|
|
|
|
os << interface->getResourceKey(resource);
|
|
|
|
dialectResources[resource.getDialect()].insert(resource);
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
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);
|
|
|
|
|
|
|
|
protected:
|
|
|
|
void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
|
|
|
|
ArrayRef<StringRef> elidedAttrs = {},
|
|
|
|
bool withKeyword = false);
|
2020-03-11 13:22:19 -07:00
|
|
|
void printNamedAttribute(NamedAttribute attr);
|
2021-05-23 14:08:31 -07:00
|
|
|
void printTrailingLocation(Location loc, bool allowAlias = true);
|
2020-01-09 12:39:26 -08:00
|
|
|
void printLocationInternal(LocationAttr loc, bool pretty = false);
|
2020-02-20 14:37:25 -08: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);
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2020-04-23 19:01:51 -07:00
|
|
|
/// Print a dense string elements attribute.
|
|
|
|
void printDenseStringElementsAttr(DenseStringElementsAttr attr);
|
|
|
|
|
2020-04-25 01:17:09 -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 printDenseIntOrFPElementsAttr(DenseIntOrFPElementsAttr attr,
|
|
|
|
bool allowHex);
|
|
|
|
|
2022-08-25 16:21:28 -07:00
|
|
|
/// Print a dense array attribute.
|
|
|
|
void printDenseArrayAttr(DenseArrayAttr attr);
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void printDialectAttribute(Attribute attr);
|
|
|
|
void printDialectType(Type type);
|
|
|
|
|
2022-05-24 01:55:27 -07:00
|
|
|
/// 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);
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// 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;
|
|
|
|
|
|
|
|
/// A set of flags to control the printer's behavior.
|
|
|
|
OpPrintingFlags printerFlags;
|
|
|
|
|
|
|
|
/// An optional printer state for the module.
|
2020-01-14 15:23:05 -08:00
|
|
|
AsmStateImpl *state;
|
2020-02-08 15:01:34 -08:00
|
|
|
|
|
|
|
/// A tracker for the number of new lines emitted during printing.
|
|
|
|
NewLineCounter 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
|
|
|
|
|
|
|
/// A set of dialect resources that were referenced during printing.
|
|
|
|
DenseMap<Dialect *, SetVector<AsmDialectResourceHandle>> dialectResources;
|
2020-01-09 12:39:26 -08:00
|
|
|
};
|
2021-09-24 19:56:01 +00:00
|
|
|
} // namespace mlir
|
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
|
|
|
}
|
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void AsmPrinter::Impl::printLocationInternal(LocationAttr loc, bool pretty) {
|
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";
|
|
|
|
})
|
|
|
|
.Case<FileLineColLoc>([&](FileLineColLoc 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());
|
2021-01-15 16:55:32 -08:00
|
|
|
os << ':' << loc.getLine() << ':' << loc.getColumn();
|
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();
|
|
|
|
if (!childLoc.isa<UnknownLoc>()) {
|
|
|
|
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) {
|
|
|
|
if (callee.isa<NameLoc>()) {
|
|
|
|
if (caller.isa<FileLineColLoc>()) {
|
|
|
|
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";
|
|
|
|
if (Attribute metadata = loc.getMetadata())
|
|
|
|
os << '<' << metadata << '>';
|
|
|
|
os << '[';
|
|
|
|
interleave(
|
|
|
|
loc.getLocations(),
|
|
|
|
[&](Location loc) { printLocationInternal(loc, pretty); },
|
|
|
|
[&]() { os << ", "; });
|
|
|
|
os << ']';
|
|
|
|
});
|
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.
|
|
|
|
static void printFloatValue(const APFloat &apValue, raw_ostream &os) {
|
|
|
|
// 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.
|
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())
|
|
|
|
return printLocationInternal(loc, /*pretty=*/true);
|
|
|
|
|
|
|
|
os << "loc(";
|
|
|
|
if (!allowAlias || !state || failed(state->getAliasState().getAlias(loc, os)))
|
2020-01-09 12:39:26 -08:00
|
|
|
printLocationInternal(loc);
|
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) {
|
|
|
|
assert(!symbolRef.empty() && "expected valid symbol reference");
|
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
|
|
|
}
|
|
|
|
|
2021-12-08 01:24:51 +00:00
|
|
|
LogicalResult AsmPrinter::Impl::printAlias(Attribute attr) {
|
|
|
|
return success(state && succeeded(state->getAliasState().getAlias(attr, os)));
|
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult AsmPrinter::Impl::printAlias(Type type) {
|
|
|
|
return success(state && succeeded(state->getAliasState().getAlias(type, os)));
|
|
|
|
}
|
|
|
|
|
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;
|
2020-01-09 12:39:26 -08:00
|
|
|
|
2022-05-16 20:21:39 +00:00
|
|
|
if (!isa<BuiltinDialect>(attr.getDialect())) {
|
|
|
|
printDialectAttribute(attr);
|
|
|
|
} else if (auto opaqueAttr = attr.dyn_cast<OpaqueAttr>()) {
|
2020-01-09 12:39:26 -08:00
|
|
|
printDialectSymbol(os, "#", opaqueAttr.getDialectNamespace(),
|
|
|
|
opaqueAttr.getAttrData());
|
2020-08-07 13:30:29 -07:00
|
|
|
} else if (attr.isa<UnitAttr>()) {
|
2020-01-09 12:39:26 -08:00
|
|
|
os << "unit";
|
2020-08-07 13:30:29 -07:00
|
|
|
return;
|
|
|
|
} else if (auto dictAttr = attr.dyn_cast<DictionaryAttr>()) {
|
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
|
|
|
|
|
|
|
} else if (auto intAttr = attr.dyn_cast<IntegerAttr>()) {
|
[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
|
|
|
|
|
|
|
} else if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
|
2020-01-09 12:39:26 -08:00
|
|
|
printFloatValue(floatAttr.getValue(), os);
|
|
|
|
|
|
|
|
// FloatAttr elides the type if F64.
|
[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 && floatAttr.getType().isF64())
|
2020-01-09 12:39:26 -08:00
|
|
|
return;
|
2020-08-07 13:30:29 -07:00
|
|
|
|
|
|
|
} else if (auto strAttr = attr.dyn_cast<StringAttr>()) {
|
2022-05-24 01:55:27 -07:00
|
|
|
printEscapedString(strAttr.getValue());
|
2020-08-07 13:30:29 -07:00
|
|
|
|
|
|
|
} else if (auto arrayAttr = attr.dyn_cast<ArrayAttr>()) {
|
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
|
|
|
|
|
|
|
} else if (auto affineMapAttr = attr.dyn_cast<AffineMapAttr>()) {
|
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
|
|
|
|
|
|
|
} else if (auto integerSetAttr = attr.dyn_cast<IntegerSetAttr>()) {
|
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
|
|
|
|
|
|
|
} else if (auto typeAttr = attr.dyn_cast<TypeAttr>()) {
|
|
|
|
printType(typeAttr.getValue());
|
|
|
|
|
|
|
|
} else if (auto refAttr = attr.dyn_cast<SymbolRefAttr>()) {
|
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
|
|
|
|
|
|
|
} else if (auto intOrFpEltAttr = attr.dyn_cast<DenseIntOrFPElementsAttr>()) {
|
|
|
|
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
|
|
|
|
|
|
|
} else if (auto strEltAttr = attr.dyn_cast<DenseStringElementsAttr>()) {
|
|
|
|
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
|
|
|
|
|
|
|
} else if (auto sparseEltAttr = attr.dyn_cast<SparseElementsAttr>()) {
|
|
|
|
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
|
|
|
}
|
[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
|
|
|
} else if (auto stridedLayoutAttr = attr.dyn_cast<StridedLayoutAttr>()) {
|
|
|
|
stridedLayoutAttr.print(os);
|
2022-08-25 16:21:28 -07:00
|
|
|
} else if (auto denseArrayAttr = attr.dyn_cast<DenseArrayAttr>()) {
|
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
|
|
|
typeElision = AttrTypeElision::Must;
|
2022-08-12 21:32:15 -04:00
|
|
|
os << "array<" << denseArrayAttr.getType().getElementType();
|
2022-08-25 16:21:28 -07:00
|
|
|
if (!denseArrayAttr.empty()) {
|
2022-08-12 21:32:15 -04:00
|
|
|
os << ": ";
|
2022-08-25 16:21:28 -07:00
|
|
|
printDenseArrayAttr(denseArrayAttr);
|
|
|
|
}
|
2022-08-11 19:05:48 -04:00
|
|
|
os << ">";
|
[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
|
|
|
} else if (auto resourceAttr = attr.dyn_cast<DenseResourceElementsAttr>()) {
|
|
|
|
os << "dense_resource<";
|
|
|
|
printResourceHandle(resourceAttr.getRawHandle());
|
|
|
|
os << ">";
|
2020-08-07 13:30:29 -07:00
|
|
|
} else if (auto locAttr = attr.dyn_cast<LocationAttr>()) {
|
|
|
|
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) {
|
|
|
|
if (auto typedAttr = attr.dyn_cast<TypedAttr>()) {
|
|
|
|
Type attrType = typedAttr.getType();
|
|
|
|
if (!attrType.isa<NoneType>()) {
|
|
|
|
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) {
|
2020-05-05 12:39:12 -07:00
|
|
|
if (auto stringAttr = attr.dyn_cast<DenseStringElementsAttr>())
|
|
|
|
return printDenseStringElementsAttr(stringAttr);
|
2020-04-23 19:01:51 -07:00
|
|
|
|
2020-05-05 12:39:12 -07:00
|
|
|
printDenseIntOrFPElementsAttr(attr.cast<DenseIntOrFPElementsAttr>(),
|
|
|
|
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.
|
2020-04-23 19:01:51 -07:00
|
|
|
auto numElements = type.getNumElements();
|
2020-05-05 12:39:22 -07:00
|
|
|
if (!attr.isSplat() && allowHex &&
|
|
|
|
shouldPrintElementsAttrWithHex(numElements)) {
|
2020-05-05 12:39:12 -07:00
|
|
|
ArrayRef<char> rawData = attr.getRawData();
|
2020-10-28 17:05:32 -07:00
|
|
|
if (llvm::support::endian::system_endianness() ==
|
|
|
|
llvm::support::endianness::big) {
|
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
|
2020-05-05 12:39:22 -07:00
|
|
|
if (ComplexType complexTy = elementType.dyn_cast<ComplexType>()) {
|
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.
|
|
|
|
if (complexElementType.isa<IntegerType>()) {
|
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 {
|
|
|
|
assert(elementType.isa<FloatType>() && "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);
|
|
|
|
llvm::LoadIntFromMemory(
|
|
|
|
value, reinterpret_cast<const uint8_t *>(data.begin() + byteSize * i),
|
|
|
|
byteSize);
|
|
|
|
// Print the data as-is or as a float.
|
|
|
|
if (type.isIntOrIndex()) {
|
|
|
|
printDenseIntElement(value, getStream(), type);
|
|
|
|
} else {
|
|
|
|
APFloat fltVal(type.cast<FloatType>().getFloatSemantics(), value);
|
|
|
|
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.
|
|
|
|
if (state && succeeded(state->getAliasState().getAlias(type, os)))
|
|
|
|
return;
|
2019-01-10 22:08:39 -08:00
|
|
|
|
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"; })
|
|
|
|
.Case<BFloat16Type>([&](Type) { os << "bf16"; })
|
|
|
|
.Case<Float16Type>([&](Type) { os << "f16"; })
|
|
|
|
.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();
|
|
|
|
if (results.size() == 1 && !results[0].isa<FunctionType>()) {
|
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) {
|
|
|
|
os << "vector<";
|
2021-10-12 14:26:01 +01:00
|
|
|
auto vShape = vectorTy.getShape();
|
|
|
|
unsigned lastDim = vShape.size();
|
|
|
|
unsigned lastFixedDim = lastDim - vectorTy.getNumScalableDims();
|
|
|
|
unsigned dimIdx = 0;
|
|
|
|
for (dimIdx = 0; dimIdx < lastFixedDim; dimIdx++)
|
|
|
|
os << vShape[dimIdx] << 'x';
|
|
|
|
if (vectorTy.isScalable()) {
|
|
|
|
os << '[';
|
|
|
|
unsigned secondToLastDim = lastDim - 1;
|
|
|
|
for (; dimIdx < secondToLastDim; dimIdx++)
|
|
|
|
os << vShape[dimIdx] << 'x';
|
|
|
|
os << vShape[dimIdx] << "]x";
|
|
|
|
}
|
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<";
|
|
|
|
for (int64_t dim : tensorTy.getShape()) {
|
|
|
|
if (ShapedType::isDynamic(dim))
|
|
|
|
os << '?';
|
|
|
|
else
|
|
|
|
os << dim;
|
|
|
|
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<";
|
|
|
|
for (int64_t dim : memrefTy.getShape()) {
|
|
|
|
if (ShapedType::isDynamic(dim))
|
|
|
|
os << '?';
|
|
|
|
else
|
|
|
|
os << dim;
|
|
|
|
os << 'x';
|
|
|
|
}
|
|
|
|
printType(memrefTy.getElementType());
|
2021-10-11 18:25:14 +03:00
|
|
|
if (!memrefTy.getLayout().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.
|
2021-11-18 05:23:32 +00:00
|
|
|
if (attr.getValue().isa<UnitAttr>())
|
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);
|
2021-09-24 19:56:01 +00:00
|
|
|
Impl subPrinter(attrNameStr, printerFlags, state);
|
|
|
|
DialectAsmPrinter printer(subPrinter);
|
2020-01-09 12:39:26 -08:00
|
|
|
dialect.printAttribute(attr, printer);
|
[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
|
|
|
|
|
|
|
// FIXME: Delete this when we no longer require a nested printer.
|
|
|
|
for (auto &it : subPrinter.dialectResources)
|
|
|
|
for (const auto &resource : it.second)
|
|
|
|
dialectResources[it.first].insert(resource);
|
2020-01-09 12:39:26 -08:00
|
|
|
}
|
|
|
|
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);
|
2021-09-24 19:56:01 +00:00
|
|
|
Impl subPrinter(typeNameStr, printerFlags, state);
|
|
|
|
DialectAsmPrinter printer(subPrinter);
|
2020-01-09 12:39:26 -08:00
|
|
|
dialect.printType(type, printer);
|
[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
|
|
|
|
|
|
|
// FIXME: Delete this when we no longer require a nested printer.
|
|
|
|
for (auto &it : subPrinter.dialectResources)
|
|
|
|
for (const auto &resource : it.second)
|
|
|
|
dialectResources[it.first].insert(resource);
|
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()));
|
|
|
|
}
|
|
|
|
|
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());
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
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: {
|
|
|
|
unsigned pos = expr.cast<AffineSymbolExpr>().getPosition();
|
|
|
|
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: {
|
|
|
|
unsigned pos = expr.cast<AffineDimExpr>().getPosition();
|
|
|
|
if (printValueName)
|
|
|
|
printValueName(pos, /*isSymbol=*/false);
|
|
|
|
else
|
|
|
|
os << 'd' << pos;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
case AffineExprKind::Constant:
|
|
|
|
os << expr.cast<AffineConstantExpr>().getValue();
|
|
|
|
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
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
auto binOp = expr.cast<AffineBinaryOpExpr>();
|
|
|
|
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.
|
|
|
|
auto rhsConst = rhsExpr.dyn_cast<AffineConstantExpr>();
|
|
|
|
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.
|
|
|
|
if (auto rhs = rhsExpr.dyn_cast<AffineBinaryOpExpr>()) {
|
|
|
|
if (rhs.getKind() == AffineExprKind::Mul) {
|
|
|
|
AffineExpr rrhsExpr = rhs.getRHS();
|
|
|
|
if (auto rrhs = rrhsExpr.dyn_cast<AffineConstantExpr>()) {
|
|
|
|
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.
|
|
|
|
if (auto rhsConst = rhsExpr.dyn_cast<AffineConstantExpr>()) {
|
|
|
|
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)
|
|
|
|
: Impl(os, state.getPrinterFlags(), &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);
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
/// Print the given operation with its indent and location.
|
|
|
|
void print(Operation *op);
|
|
|
|
/// Print the bare location, not including indentation/location/etc.
|
|
|
|
void printOperation(Operation *op);
|
|
|
|
/// Print 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
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
state->getSSANameState().shadowRegionArgs(region, namesToUse);
|
|
|
|
}
|
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)>;
|
|
|
|
|
|
|
|
ResourceBuilder(OperationPrinter &p, PrintFn printFn)
|
|
|
|
: p(p), printFn(printFn) {}
|
|
|
|
~ResourceBuilder() override = default;
|
|
|
|
|
|
|
|
void buildBool(StringRef key, bool data) final {
|
|
|
|
printFn(key, [&](raw_ostream &os) { p.os << (data ? "true" : "false"); });
|
|
|
|
}
|
|
|
|
|
|
|
|
void buildString(StringRef key, StringRef data) final {
|
|
|
|
printFn(key, [&](raw_ostream &os) { p.printEscapedString(data); });
|
|
|
|
}
|
|
|
|
|
|
|
|
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:
|
|
|
|
OperationPrinter &p;
|
|
|
|
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.
|
|
|
|
state->getAliasState().printNonDeferredAliases(os, newLine);
|
2020-01-14 15:23:05 -08:00
|
|
|
|
|
|
|
// Print the module.
|
2020-12-03 15:46:23 -08:00
|
|
|
print(op);
|
2020-11-12 23:33:43 -08:00
|
|
|
os << newLine;
|
|
|
|
|
|
|
|
// Output the aliases at the top level that can be deferred.
|
|
|
|
state->getAliasState().printDeferredAliases(os, 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;
|
|
|
|
auto processProvider = [&](StringRef dictName, StringRef name, auto &provider,
|
|
|
|
auto &&...providerArgs) {
|
|
|
|
bool hadEntry = false;
|
|
|
|
auto printFn = [&](StringRef key, ResourceBuilder::ValueFn valueFn) {
|
|
|
|
checkAddMetadataDict();
|
|
|
|
|
|
|
|
// Emit the top-level resource entry if we haven't yet.
|
|
|
|
if (!std::exchange(hadResource, true))
|
|
|
|
os << " " << dictName << "_resources: {" << newLine;
|
|
|
|
// Emit the parent resource entry if we haven't yet.
|
|
|
|
if (!std::exchange(hadEntry, true))
|
|
|
|
os << " " << name << ": {" << newLine;
|
|
|
|
else
|
|
|
|
os << "," << newLine;
|
|
|
|
|
|
|
|
os << " " << key << ": ";
|
|
|
|
valueFn(os);
|
|
|
|
};
|
|
|
|
ResourceBuilder entryBuilder(*this, printFn);
|
|
|
|
provider.buildResources(op, providerArgs..., entryBuilder);
|
|
|
|
|
|
|
|
if (hadEntry)
|
|
|
|
os << newLine << " }";
|
|
|
|
};
|
|
|
|
|
|
|
|
// Print the `dialect_resources` section if we have any dialects with
|
|
|
|
// resources.
|
|
|
|
for (const OpAsmDialectInterface &interface : state->getDialectInterfaces()) {
|
|
|
|
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.
|
|
|
|
hadResource = false;
|
|
|
|
for (const auto &printer : state->getResourcePrinters())
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
void OperationPrinter::print(Operation *op) {
|
2020-02-08 15:01:34 -08:00
|
|
|
// Track the location of this operation.
|
|
|
|
state->registerOperationLocation(op, newLine.curLine, currentIndent);
|
|
|
|
|
2020-01-09 12:39:26 -08:00
|
|
|
os.indent(currentIndent);
|
|
|
|
printOperation(op);
|
|
|
|
printTrailingLocation(op->getLoc());
|
2022-04-22 18:52:54 +00:00
|
|
|
if (printerFlags.shouldPrintValueUsers())
|
|
|
|
printUsersComment(op);
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
|
2019-07-03 13:21:24 -07:00
|
|
|
void OperationPrinter::printOperation(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.
|
2020-01-09 12:39:26 -08:00
|
|
|
ArrayRef<int> resultGroups = state->getSSANameState().getOpResultGroups(op);
|
|
|
|
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 << " = ";
|
|
|
|
}
|
|
|
|
|
2020-01-14 15:09:39 -08:00
|
|
|
// If requested, always print the generic form.
|
|
|
|
if (!printerFlags.shouldPrintGenericOpForm()) {
|
2021-11-17 21:50:28 +00:00
|
|
|
// Check to see if this is a known operation. If so, use the registered
|
2020-01-14 15:09:39 -08:00
|
|
|
// custom printer hook.
|
2021-11-17 21:50:28 +00:00
|
|
|
if (auto opInfo = op->getRegisteredInfo()) {
|
2021-08-28 03:03:49 +00:00
|
|
|
opInfo->printAssembly(op, *this, defaultDialectStack.back());
|
2020-01-14 15:09:39 -08:00
|
|
|
return;
|
|
|
|
}
|
2021-03-23 00:33:03 +00:00
|
|
|
// Otherwise try to dispatch to the dialect, if available.
|
|
|
|
if (Dialect *dialect = op->getDialect()) {
|
2021-08-28 03:02:55 +00:00
|
|
|
if (auto opPrinter = dialect->getOperationPrinter(op)) {
|
2021-08-28 03:03:15 +00:00
|
|
|
// Print the op name first.
|
|
|
|
StringRef name = op->getName().getStringRef();
|
2022-05-19 16:13:51 +02:00
|
|
|
// Only drop the default dialect prefix when it cannot lead to
|
|
|
|
// ambiguities.
|
|
|
|
if (name.count('.') == 1)
|
|
|
|
name.consume_front((defaultDialectStack.back() + ".").str());
|
2022-05-24 01:55:27 -07:00
|
|
|
os << name;
|
|
|
|
|
2021-08-28 03:03:15 +00:00
|
|
|
// Print the rest of the op now.
|
2021-08-28 03:02:55 +00:00
|
|
|
opPrinter(op, *this);
|
2021-03-23 00:33:03 +00:00
|
|
|
return;
|
2021-08-28 03:02:55 +00:00
|
|
|
}
|
2021-03-23 00:33:03 +00:00
|
|
|
}
|
2018-12-28 11:41:56 -08:00
|
|
|
}
|
|
|
|
|
2019-01-23 11:26:56 -08:00
|
|
|
// Otherwise print with the generic assembly form.
|
2021-08-28 03:03:15 +00:00
|
|
|
printGenericOp(op, /*printOpName=*/true);
|
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;
|
|
|
|
for (auto &indexedUser : enumerate(value.getUsers())) {
|
|
|
|
if (userSet.insert(indexedUser.value()).second)
|
|
|
|
printUserIDs(indexedUser.value(), indexedUser.index());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void OperationPrinter::printUserIDs(Operation *user, bool prefixComma) {
|
|
|
|
if (prefixComma)
|
|
|
|
os << ", ";
|
|
|
|
|
|
|
|
if (!user->getNumResults()) {
|
|
|
|
printOperationID(user);
|
|
|
|
} else {
|
|
|
|
interleaveComma(user->getResults(),
|
|
|
|
[this](Value result) { printValueID(result); });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 << ']';
|
|
|
|
}
|
|
|
|
|
2019-05-06 01:40:13 -07:00
|
|
|
// Print regions.
|
|
|
|
if (op->getNumRegions() != 0) {
|
|
|
|
os << " (";
|
|
|
|
interleaveComma(op->getRegions(), [&](Region ®ion) {
|
|
|
|
printRegion(region, /*printEntryBlockArgs=*/true,
|
2021-03-11 23:58:02 +00:00
|
|
|
/*printBlockTerminators=*/true, /*printEmptyBlock=*/true);
|
2019-05-06 01:40:13 -07:00
|
|
|
});
|
|
|
|
os << ')';
|
|
|
|
}
|
|
|
|
|
2018-12-28 11:41:56 -08:00
|
|
|
auto attrs = op->getAttrs();
|
|
|
|
printOptionalAttrDict(attrs);
|
|
|
|
|
|
|
|
// 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-02-07 21:10:18 +00: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-02-07 21:10:18 +00:00
|
|
|
predIDs.push_back(state->getSSANameState().getBlockInfo(pred));
|
|
|
|
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) {
|
|
|
|
print(&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 {
|
|
|
|
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 {
|
|
|
|
state->getSSANameState().printOperationID(op, streamOverride ? *streamOverride
|
|
|
|
: os);
|
|
|
|
}
|
|
|
|
|
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) {
|
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) {
|
|
|
|
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
|
|
|
|
2018-07-18 16:29:21 -07:00
|
|
|
void Attribute::print(raw_ostream &os) const {
|
2021-09-24 19:56:01 +00:00
|
|
|
AsmPrinter::Impl(os).printAttribute(*this);
|
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
|
|
|
|
2021-09-24 19:56:01 +00:00
|
|
|
void Type::print(raw_ostream &os) const {
|
|
|
|
AsmPrinter::Impl(os).printType(*this);
|
|
|
|
}
|
2018-07-17 16:56:54 -07:00
|
|
|
|
2021-06-16 15:31:20 -07:00
|
|
|
void Type::dump() const { print(llvm::errs()); }
|
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;
|
|
|
|
}
|
2021-09-24 19:56:01 +00:00
|
|
|
AsmPrinter::Impl(os).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;
|
|
|
|
}
|
2021-09-24 19:56:01 +00:00
|
|
|
AsmPrinter::Impl(os).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 {
|
2021-09-24 19:56:01 +00:00
|
|
|
AsmPrinter::Impl(os).printIntegerSet(*this);
|
2018-08-07 14:24:38 -07:00
|
|
|
}
|
|
|
|
|
2022-03-07 07:49:46 -08:00
|
|
|
void Value::print(raw_ostream &os) { print(os, OpPrintingFlags()); }
|
|
|
|
void Value::print(raw_ostream &os, const OpPrintingFlags &flags) {
|
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.
|
2020-09-15 10:58:45 +05:30
|
|
|
BlockArgument arg = this->cast<BlockArgument>();
|
|
|
|
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
|
|
|
}
|
2020-01-14 15:23:05 -08:00
|
|
|
void Value::print(raw_ostream &os, AsmState &state) {
|
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.
|
2020-09-15 10:58:45 +05:30
|
|
|
BlockArgument arg = this->cast<BlockArgument>();
|
|
|
|
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
|
|
|
|
2019-09-27 16:20:04 -07:00
|
|
|
void Value::dump() {
|
|
|
|
print(llvm::errs());
|
|
|
|
llvm::errs() << "\n";
|
|
|
|
}
|
2018-08-02 17:16:58 -07:00
|
|
|
|
2020-01-14 15:23:05 -08:00
|
|
|
void Value::printAsOperand(raw_ostream &os, AsmState &state) {
|
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);
|
|
|
|
}
|
|
|
|
|
2021-07-10 16:39:44 +00:00
|
|
|
void Operation::print(raw_ostream &os, const OpPrintingFlags &printerFlags) {
|
2020-12-03 15:46:23 -08:00
|
|
|
// If this is a top level operation, we also print aliases.
|
2021-07-10 16:39:44 +00:00
|
|
|
if (!getParent() && !printerFlags.shouldUseLocalScope()) {
|
|
|
|
AsmState state(this, printerFlags);
|
|
|
|
state.getImpl().initializeAliases(this);
|
2022-02-15 17:09:08 -08:00
|
|
|
print(os, state);
|
2020-12-03 15:46:23 -08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-04-06 11:04:22 -07:00
|
|
|
// Find the operation to number from based upon the provided flags.
|
2021-02-09 11:41:10 -08:00
|
|
|
Operation *op = this;
|
2021-07-10 16:39:44 +00:00
|
|
|
bool shouldUseLocalScope = printerFlags.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);
|
2018-12-28 11:41:56 -08:00
|
|
|
|
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());
|
|
|
|
if (!getParent() && !state.getPrinterFlags().shouldUseLocalScope())
|
2020-12-03 15:46:23 -08:00
|
|
|
printer.printTopLevelOperation(this);
|
|
|
|
else
|
|
|
|
printer.print(this);
|
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
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|