#include "Parser.h"
#include "AsmParserImpl.h"
#include "mlir/AsmParser/AsmParser.h"
#include "mlir/AsmParser/AsmParserState.h"
#include "mlir/AsmParser/CodeComplete.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/AsmState.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/OpDefinition.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/OwningOpRef.h"
#include "mlir/IR/Region.h"
#include "mlir/IR/Value.h"
#include "mlir/IR/Verifier.h"
#include "mlir/IR/Visitors.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/TypeID.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Alignment.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace mlir;
using namespace mlir::detail;
AsmParserCodeCompleteContext::~AsmParserCodeCompleteContext() = default;
ParseResult
Parser::parseCommaSeparatedList(Delimiter delimiter,
function_ref<ParseResult()> parseElementFn,
StringRef contextMessage) {
switch (delimiter) {
case Delimiter::None:
break;
case Delimiter::OptionalParen:
if (getToken().isNot(Token::l_paren))
return success();
[[fallthrough]];
case Delimiter::Paren:
if (parseToken(Token::l_paren, "expected '('" + contextMessage))
return failure();
if (consumeIf(Token::r_paren))
return success();
break;
case Delimiter::OptionalLessGreater:
if (getToken().isNot(Token::less))
return success();
[[fallthrough]];
case Delimiter::LessGreater:
if (parseToken(Token::less, "expected '<'" + contextMessage))
return success();
if (consumeIf(Token::greater))
return success();
break;
case Delimiter::OptionalSquare:
if (getToken().isNot(Token::l_square))
return success();
[[fallthrough]];
case Delimiter::Square:
if (parseToken(Token::l_square, "expected '['" + contextMessage))
return failure();
if (consumeIf(Token::r_square))
return success();
break;
case Delimiter::OptionalBraces:
if (getToken().isNot(Token::l_brace))
return success();
[[fallthrough]];
case Delimiter::Braces:
if (parseToken(Token::l_brace, "expected '{'" + contextMessage))
return failure();
if (consumeIf(Token::r_brace))
return success();
break;
}
if (parseElementFn())
return failure();
while (consumeIf(Token::comma)) {
if (parseElementFn())
return failure();
}
switch (delimiter) {
case Delimiter::None:
return success();
case Delimiter::OptionalParen:
case Delimiter::Paren:
return parseToken(Token::r_paren, "expected ')'" + contextMessage);
case Delimiter::OptionalLessGreater:
case Delimiter::LessGreater:
return parseToken(Token::greater, "expected '>'" + contextMessage);
case Delimiter::OptionalSquare:
case Delimiter::Square:
return parseToken(Token::r_square, "expected ']'" + contextMessage);
case Delimiter::OptionalBraces:
case Delimiter::Braces:
return parseToken(Token::r_brace, "expected '}'" + contextMessage);
}
llvm_unreachable("Unknown delimiter");
}
ParseResult
Parser::parseCommaSeparatedListUntil(Token::Kind rightToken,
function_ref<ParseResult()> parseElement,
bool allowEmptyList) {
if (getToken().is(rightToken)) {
if (!allowEmptyList)
return emitWrongTokenError("expected list element");
consumeToken(rightToken);
return success();
}
if (parseCommaSeparatedList(parseElement) ||
parseToken(rightToken, "expected ',' or '" +
Token::getTokenSpelling(rightToken) + "'"))
return failure();
return success();
}
InFlightDiagnostic Parser::emitError(const Twine &message) {
auto loc = state.curToken.getLoc();
if (state.curToken.isNot(Token::eof))
return emitError(loc, message);
return emitError(SMLoc::getFromPointer(loc.getPointer() - 1), message);
}
InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) {
auto diag = mlir::emitError(getEncodedSourceLocation(loc), message);
if (getToken().is(Token::error))
diag.abandon();
return diag;
}
InFlightDiagnostic Parser::emitWrongTokenError(const Twine &message) {
auto loc = state.curToken.getLoc();
if (state.curToken.is(Token::eof))
loc = SMLoc::getFromPointer(loc.getPointer() - 1);
auto originalLoc = loc;
const char *bufferStart = state.lex.getBufferBegin();
const char *curPtr = loc.getPointer();
StringRef startOfBuffer(bufferStart, curPtr - bufferStart);
while (true) {
startOfBuffer = startOfBuffer.rtrim(" \t");
if (startOfBuffer.empty())
return emitError(originalLoc, message);
if (startOfBuffer.back() != '\n' && startOfBuffer.back() != '\r')
return emitError(SMLoc::getFromPointer(startOfBuffer.end()), message);
startOfBuffer = startOfBuffer.drop_back();
auto prevLine = startOfBuffer;
size_t newLineIndex = prevLine.find_last_of("\n\r");
if (newLineIndex != StringRef::npos)
prevLine = prevLine.drop_front(newLineIndex);
size_t commentStart = prevLine.find("//");
if (commentStart != StringRef::npos)
startOfBuffer = startOfBuffer.drop_back(prevLine.size() - commentStart);
}
}
ParseResult Parser::parseToken(Token::Kind expectedToken,
const Twine &message) {
if (consumeIf(expectedToken))
return success();
return emitWrongTokenError(message);
}
OptionalParseResult Parser::parseOptionalInteger(APInt &result) {
if (consumeIf(Token::kw_false)) {
result = false;
return success();
}
if (consumeIf(Token::kw_true)) {
result = true;
return success();
}
Token curToken = getToken();
if (curToken.isNot(Token::integer, Token::minus))
return std::nullopt;
bool negative = consumeIf(Token::minus);
Token curTok = getToken();
if (parseToken(Token::integer, "expected integer value"))
return failure();
StringRef spelling = curTok.getSpelling();
bool isHex = spelling.size() > 1 && spelling[1] == 'x';
if (spelling.getAsInteger(isHex ? 0 : 10, result))
return emitError(curTok.getLoc(), "integer value too large");
if (result.isNegative())
result = result.zext(result.getBitWidth() + 1);
if (negative)
result.negate();
return success();
}
ParseResult Parser::parseFloatFromIntegerLiteral(
std::optional<APFloat> &result, const Token &tok, bool isNegative,
const llvm::fltSemantics &semantics, size_t typeSizeInBits) {
SMLoc loc = tok.getLoc();
StringRef spelling = tok.getSpelling();
bool isHex = spelling.size() > 1 && spelling[1] == 'x';
if (!isHex) {
return emitError(loc, "unexpected decimal integer literal for a "
"floating point value")
.attachNote()
<< "add a trailing dot to make the literal a float";
}
if (isNegative) {
return emitError(loc, "hexadecimal float literal should not have a "
"leading minus");
}
APInt intValue;
tok.getSpelling().getAsInteger(isHex ? 0 : 10, intValue);
if (intValue.getActiveBits() > typeSizeInBits)
return emitError(loc, "hexadecimal float constant out of range for type");
APInt truncatedValue(typeSizeInBits, intValue.getNumWords(),
intValue.getRawData());
result.emplace(semantics, truncatedValue);
return success();
}
ParseResult Parser::parseOptionalKeyword(StringRef *keyword) {
if (!isCurrentTokenAKeyword())
return failure();
*keyword = getTokenSpelling();
consumeToken();
return success();
}
FailureOr<AsmDialectResourceHandle>
Parser::parseResourceHandle(const OpAsmDialectInterface *dialect,
StringRef &name) {
assert(dialect && "expected valid dialect interface");
SMLoc nameLoc = getToken().getLoc();
if (failed(parseOptionalKeyword(&name)))
return emitError("expected identifier key for 'resource' entry");
auto &resources = getState().symbols.dialectResources;
std::pair<std::string, AsmDialectResourceHandle> &entry =
resources[dialect][name];
if (entry.first.empty()) {
FailureOr<AsmDialectResourceHandle> result = dialect->declareResource(name);
if (failed(result)) {
return emitError(nameLoc)
<< "unknown 'resource' key '" << name << "' for dialect '"
<< dialect->getDialect()->getNamespace() << "'";
}
entry.first = dialect->getResourceKey(*result);
entry.second = *result;
}
name = entry.first;
return entry.second;
}
FailureOr<AsmDialectResourceHandle>
Parser::parseResourceHandle(Dialect *dialect) {
const auto *interface = dyn_cast<OpAsmDialectInterface>(dialect);
if (!interface) {
return emitError() << "dialect '" << dialect->getNamespace()
<< "' does not expect resource handles";
}
StringRef resourceName;
return parseResourceHandle(interface, resourceName);
}
ParseResult Parser::codeCompleteDialectName() {
state.codeCompleteContext->completeDialectName();
return failure();
}
ParseResult Parser::codeCompleteOperationName(StringRef dialectName) {
if (dialectName.empty() || dialectName.contains('.'))
return failure();
state.codeCompleteContext->completeOperationName(dialectName);
return failure();
}
ParseResult Parser::codeCompleteDialectOrElidedOpName(SMLoc loc) {
auto shouldIgnoreOpCompletion = [&]() {
const char *bufBegin = state.lex.getBufferBegin();
const char *it = loc.getPointer() - 1;
for (; it > bufBegin && *it != '\n'; --it)
if (!StringRef(" \t\r").contains(*it))
return true;
return false;
};
if (shouldIgnoreOpCompletion())
return failure();
(void)codeCompleteDialectName();
return codeCompleteOperationName(state.defaultDialectStack.back());
}
ParseResult Parser::codeCompleteStringDialectOrOperationName(StringRef name) {
if (name.empty())
return codeCompleteDialectName();
if (name.consume_back("."))
return codeCompleteOperationName(name);
return failure();
}
ParseResult Parser::codeCompleteExpectedTokens(ArrayRef<StringRef> tokens) {
state.codeCompleteContext->completeExpectedTokens(tokens, false);
return failure();
}
ParseResult Parser::codeCompleteOptionalTokens(ArrayRef<StringRef> tokens) {
state.codeCompleteContext->completeExpectedTokens(tokens, true);
return failure();
}
Attribute Parser::codeCompleteAttribute() {
state.codeCompleteContext->completeAttribute(
state.symbols.attributeAliasDefinitions);
return {};
}
Type Parser::codeCompleteType() {
state.codeCompleteContext->completeType(state.symbols.typeAliasDefinitions);
return {};
}
Attribute
Parser::codeCompleteDialectSymbol(const llvm::StringMap<Attribute> &aliases) {
state.codeCompleteContext->completeDialectAttributeOrAlias(aliases);
return {};
}
Type Parser::codeCompleteDialectSymbol(const llvm::StringMap<Type> &aliases) {
state.codeCompleteContext->completeDialectTypeOrAlias(aliases);
return {};
}
namespace {
class OperationParser : public Parser {
public:
OperationParser(ParserState &state, ModuleOp topLevelOp);
~OperationParser();
ParseResult finalize();
using UnresolvedOperand = OpAsmParser::UnresolvedOperand;
using Argument = OpAsmParser::Argument;
struct DeferredLocInfo {
SMLoc loc;
StringRef identifier;
};
void pushSSANameScope(bool isIsolated);
ParseResult popSSANameScope();
ParseResult addDefinition(UnresolvedOperand useInfo, Value value);
ParseResult
parseOptionalSSAUseList(SmallVectorImpl<UnresolvedOperand> &results);
ParseResult parseSSAUse(UnresolvedOperand &result,
bool allowResultNumber = true);
Value resolveSSAUse(UnresolvedOperand useInfo, Type type);
ParseResult parseSSADefOrUseAndType(
function_ref<ParseResult(UnresolvedOperand, Type)> action);
ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results);
std::optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) {
auto &values = isolatedNameScopes.back().values;
if (!values.count(name) || number >= values[name].size())
return {};
if (values[name][number].value)
return values[name][number].loc;
return {};
}
ParseResult parseOperation();
ParseResult parseSuccessor(Block *&dest);
ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations);
Operation *parseGenericOperation();
ParseResult parseGenericOperationAfterOpName(
OperationState &result,
std::optional<ArrayRef<UnresolvedOperand>> parsedOperandUseInfo =
std::nullopt,
std::optional<ArrayRef<Block *>> parsedSuccessors = std::nullopt,
std::optional<MutableArrayRef<std::unique_ptr<Region>>> parsedRegions =
std::nullopt,
std::optional<ArrayRef<NamedAttribute>> parsedAttributes = std::nullopt,
std::optional<Attribute> propertiesAttribute = std::nullopt,
std::optional<FunctionType> parsedFnType = std::nullopt);
Operation *parseGenericOperation(Block *insertBlock,
Block::iterator insertPt);
using OpOrArgument = llvm::PointerUnion<Operation *, BlockArgument>;
ParseResult parseTrailingLocationSpecifier(OpOrArgument opOrArgument);
ParseResult parseLocationAlias(LocationAttr &loc);
using ResultRecord = std::tuple<StringRef, unsigned, SMLoc>;
Operation *parseCustomOperation(ArrayRef<ResultRecord> resultIDs);
FailureOr<OperationName> parseCustomOperationName();
ParseResult parseRegion(Region ®ion, ArrayRef<Argument> entryArguments,
bool isIsolatedNameScope = false);
ParseResult parseRegionBody(Region ®ion, SMLoc startLoc,
ArrayRef<Argument> entryArguments,
bool isIsolatedNameScope);
ParseResult parseBlock(Block *&block);
ParseResult parseBlockBody(Block *block);
ParseResult parseOptionalBlockArgList(Block *owner);
Block *getBlockNamed(StringRef name, SMLoc loc);
ParseResult codeCompleteSSAUse();
ParseResult codeCompleteBlock();
private:
struct BlockDefinition {
Block *block;
SMLoc loc;
};
struct ValueDefinition {
Value value;
SMLoc loc;
};
BlockDefinition &getBlockInfoByName(StringRef name) {
return blocksByName.back()[name];
}
void insertForwardRef(Block *block, SMLoc loc) {
forwardRef.back().try_emplace(block, loc);
}
bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); }
void recordDefinition(StringRef def);
SmallVectorImpl<ValueDefinition> &getSSAValueEntry(StringRef name);
Value createForwardRefPlaceholder(SMLoc loc, Type type);
bool isForwardRefPlaceholder(Value value) {
return forwardRefPlaceholders.count(value);
}
struct IsolatedSSANameScope {
void recordDefinition(StringRef def) {
definitionsPerScope.back().insert(def);
}
void pushSSANameScope() { definitionsPerScope.push_back({}); }
void popSSANameScope() {
for (auto &def : definitionsPerScope.pop_back_val())
values.erase(def.getKey());
}
llvm::StringMap<SmallVector<ValueDefinition, 1>> values;
SmallVector<llvm::StringSet<>, 2> definitionsPerScope;
};
SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes;
SmallVector<DenseMap<StringRef, BlockDefinition>, 2> blocksByName;
SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef;
DenseMap<Value, SMLoc> forwardRefPlaceholders;
std::vector<DeferredLocInfo> deferredLocsReferences;
OpBuilder opBuilder;
Operation *topLevelOp;
};
}
MLIR_DECLARE_EXPLICIT_TYPE_ID(OperationParser::DeferredLocInfo *)
MLIR_DEFINE_EXPLICIT_TYPE_ID(OperationParser::DeferredLocInfo *)
OperationParser::OperationParser(ParserState &state, ModuleOp topLevelOp)
: Parser(state), opBuilder(topLevelOp.getRegion()), topLevelOp(topLevelOp) {
pushSSANameScope(true);
if (state.asmState)
state.asmState->initialize(topLevelOp);
}
OperationParser::~OperationParser() {
for (auto &fwd : forwardRefPlaceholders) {
fwd.first.dropAllUses();
fwd.first.getDefiningOp()->destroy();
}
for (const auto &scope : forwardRef) {
for (const auto &fwd : scope) {
fwd.first->dropAllUses();
delete fwd.first;
}
}
}
ParseResult OperationParser::finalize() {
if (!forwardRefPlaceholders.empty()) {
SmallVector<const char *, 4> errors;
for (auto entry : forwardRefPlaceholders)
errors.push_back(entry.second.getPointer());
llvm::array_pod_sort(errors.begin(), errors.end());
for (const char *entry : errors) {
auto loc = SMLoc::getFromPointer(entry);
emitError(loc, "use of undeclared SSA value name");
}
return failure();
}
auto &attributeAliases = state.symbols.attributeAliasDefinitions;
auto locID = TypeID::get<DeferredLocInfo *>();
auto resolveLocation = [&, this](auto &opOrArgument) -> LogicalResult {
auto fwdLoc = dyn_cast<OpaqueLoc>(opOrArgument.getLoc());
if (!fwdLoc || fwdLoc.getUnderlyingTypeID() != locID)
return success();
auto locInfo = deferredLocsReferences[fwdLoc.getUnderlyingLocation()];
Attribute attr = attributeAliases.lookup(locInfo.identifier);
if (!attr)
return this->emitError(locInfo.loc)
<< "operation location alias was never defined";
auto locAttr = dyn_cast<LocationAttr>(attr);
if (!locAttr)
return this->emitError(locInfo.loc)
<< "expected location, but found '" << attr << "'";
opOrArgument.setLoc(locAttr);
return success();
};
auto walkRes = topLevelOp->walk([&](Operation *op) {
if (failed(resolveLocation(*op)))
return WalkResult::interrupt();
for (Region ®ion : op->getRegions())
for (Block &block : region.getBlocks())
for (BlockArgument arg : block.getArguments())
if (failed(resolveLocation(arg)))
return WalkResult::interrupt();
return WalkResult::advance();
});
if (walkRes.wasInterrupted())
return failure();
if (failed(popSSANameScope()))
return failure();
if (state.config.shouldVerifyAfterParse() && failed(verify(topLevelOp)))
return failure();
if (state.asmState)
state.asmState->finalize(topLevelOp);
return success();
}
void OperationParser::pushSSANameScope(bool isIsolated) {
blocksByName.push_back(DenseMap<StringRef, BlockDefinition>());
forwardRef.push_back(DenseMap<Block *, SMLoc>());
if (isIsolated)
isolatedNameScopes.push_back({});
isolatedNameScopes.back().pushSSANameScope();
}
ParseResult OperationParser::popSSANameScope() {
auto forwardRefInCurrentScope = forwardRef.pop_back_val();
if (!forwardRefInCurrentScope.empty()) {
SmallVector<std::pair<const char *, Block *>, 4> errors;
for (auto entry : forwardRefInCurrentScope) {
errors.push_back({entry.second.getPointer(), entry.first});
topLevelOp->getRegion(0).push_back(entry.first);
}
llvm::array_pod_sort(errors.begin(), errors.end());
for (auto entry : errors) {
auto loc = SMLoc::getFromPointer(entry.first);
emitError(loc, "reference to an undefined block");
}
return failure();
}
auto ¤tNameScope = isolatedNameScopes.back();
if (currentNameScope.definitionsPerScope.size() == 1)
isolatedNameScopes.pop_back();
else
currentNameScope.popSSANameScope();
blocksByName.pop_back();
return success();
}
ParseResult OperationParser::addDefinition(UnresolvedOperand useInfo,
Value value) {
auto &entries = getSSAValueEntry(useInfo.name);
if (entries.size() <= useInfo.number)
entries.resize(useInfo.number + 1);
if (auto existing = entries[useInfo.number].value) {
if (!isForwardRefPlaceholder(existing)) {
return emitError(useInfo.location)
.append("redefinition of SSA value '", useInfo.name, "'")
.attachNote(getEncodedSourceLocation(entries[useInfo.number].loc))
.append("previously defined here");
}
if (existing.getType() != value.getType()) {
return emitError(useInfo.location)
.append("definition of SSA value '", useInfo.name, "#",
useInfo.number, "' has type ", value.getType())
.attachNote(getEncodedSourceLocation(entries[useInfo.number].loc))
.append("previously used here with type ", existing.getType());
}
existing.replaceAllUsesWith(value);
existing.getDefiningOp()->destroy();
forwardRefPlaceholders.erase(existing);
if (state.asmState)
state.asmState->refineDefinition(existing, value);
}
entries[useInfo.number] = {value, useInfo.location};
recordDefinition(useInfo.name);
return success();
}
ParseResult OperationParser::parseOptionalSSAUseList(
SmallVectorImpl<UnresolvedOperand> &results) {
if (!getToken().isOrIsCodeCompletionFor(Token::percent_identifier))
return success();
return parseCommaSeparatedList([&]() -> ParseResult {
UnresolvedOperand result;
if (parseSSAUse(result))
return failure();
results.push_back(result);
return success();
});
}
ParseResult OperationParser::parseSSAUse(UnresolvedOperand &result,
bool allowResultNumber) {
if (getToken().isCodeCompletion())
return codeCompleteSSAUse();
result.name = getTokenSpelling();
result.number = 0;
result.location = getToken().getLoc();
if (parseToken(Token::percent_identifier, "expected SSA operand"))
return failure();
if (getToken().is(Token::hash_identifier)) {
if (!allowResultNumber)
return emitError("result number not allowed in argument list");
if (auto value = getToken().getHashIdentifierNumber())
result.number = *value;
else
return emitError("invalid SSA value result number");
consumeToken(Token::hash_identifier);
}
return success();
}
Value OperationParser::resolveSSAUse(UnresolvedOperand useInfo, Type type) {
auto &entries = getSSAValueEntry(useInfo.name);
auto maybeRecordUse = [&](Value value) {
if (state.asmState)
state.asmState->addUses(value, useInfo.location);
return value;
};
if (useInfo.number < entries.size() && entries[useInfo.number].value) {
Value result = entries[useInfo.number].value;
if (result.getType() == type)
return maybeRecordUse(result);
emitError(useInfo.location, "use of value '")
.append(useInfo.name,
"' expects different type than prior uses: ", type, " vs ",
result.getType())
.attachNote(getEncodedSourceLocation(entries[useInfo.number].loc))
.append("prior use here");
return nullptr;
}
if (entries.size() <= useInfo.number)
entries.resize(useInfo.number + 1);
if (entries[0].value && !isForwardRefPlaceholder(entries[0].value))
return (emitError(useInfo.location, "reference to invalid result number"),
nullptr);
Value result = createForwardRefPlaceholder(useInfo.location, type);
entries[useInfo.number] = {result, useInfo.location};
return maybeRecordUse(result);
}
ParseResult OperationParser::parseSSADefOrUseAndType(
function_ref<ParseResult(UnresolvedOperand, Type)> action) {
UnresolvedOperand useInfo;
if (parseSSAUse(useInfo) ||
parseToken(Token::colon, "expected ':' and type for SSA operand"))
return failure();
auto type = parseType();
if (!type)
return failure();
return action(useInfo, type);
}
ParseResult OperationParser::parseOptionalSSAUseAndTypeList(
SmallVectorImpl<Value> &results) {
SmallVector<UnresolvedOperand, 4> valueIDs;
if (parseOptionalSSAUseList(valueIDs))
return failure();
if (valueIDs.empty())
return success();
SmallVector<Type, 4> types;
if (parseToken(Token::colon, "expected ':' in operand list") ||
parseTypeListNoParens(types))
return failure();
if (valueIDs.size() != types.size())
return emitError("expected ")
<< valueIDs.size() << " types to match operand list";
results.reserve(valueIDs.size());
for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) {
if (auto value = resolveSSAUse(valueIDs[i], types[i]))
results.push_back(value);
else
return failure();
}
return success();
}
void OperationParser::recordDefinition(StringRef def) {
isolatedNameScopes.back().recordDefinition(def);
}
auto OperationParser::getSSAValueEntry(StringRef name)
-> SmallVectorImpl<ValueDefinition> & {
return isolatedNameScopes.back().values[name];
}
Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) {
auto name = OperationName("builtin.unrealized_conversion_cast", getContext());
auto *op = Operation::create(
getEncodedSourceLocation(loc), name, type, {},
std::nullopt, nullptr, {},
0);
forwardRefPlaceholders[op->getResult(0)] = loc;
return op->getResult(0);
}
ParseResult OperationParser::parseOperation() {
auto loc = getToken().getLoc();
SmallVector<ResultRecord, 1> resultIDs;
size_t numExpectedResults = 0;
if (getToken().is(Token::percent_identifier)) {
auto parseNextResult = [&]() -> ParseResult {
Token nameTok = getToken();
if (parseToken(Token::percent_identifier,
"expected valid ssa identifier"))
return failure();
size_t expectedSubResults = 1;
if (consumeIf(Token::colon)) {
if (!getToken().is(Token::integer))
return emitWrongTokenError("expected integer number of results");
auto val = getToken().getUInt64IntegerValue();
if (!val || *val < 1)
return emitError(
"expected named operation to have at least 1 result");
consumeToken(Token::integer);
expectedSubResults = *val;
}
resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults,
nameTok.getLoc());
numExpectedResults += expectedSubResults;
return success();
};
if (parseCommaSeparatedList(parseNextResult))
return failure();
if (parseToken(Token::equal, "expected '=' after SSA name"))
return failure();
}
Operation *op;
Token nameTok = getToken();
if (nameTok.is(Token::bare_identifier) || nameTok.isKeyword())
op = parseCustomOperation(resultIDs);
else if (nameTok.is(Token::string))
op = parseGenericOperation();
else if (nameTok.isCodeCompletionFor(Token::string))
return codeCompleteStringDialectOrOperationName(nameTok.getStringValue());
else if (nameTok.isCodeCompletion())
return codeCompleteDialectOrElidedOpName(loc);
else
return emitWrongTokenError("expected operation name in quotes");
if (!op)
return failure();
if (!resultIDs.empty()) {
if (op->getNumResults() == 0)
return emitError(loc, "cannot name an operation with no results");
if (numExpectedResults != op->getNumResults())
return emitError(loc, "operation defines ")
<< op->getNumResults() << " results but was provided "
<< numExpectedResults << " to bind";
if (state.asmState) {
unsigned resultIt = 0;
SmallVector<std::pair<unsigned, SMLoc>> asmResultGroups;
asmResultGroups.reserve(resultIDs.size());
for (ResultRecord &record : resultIDs) {
asmResultGroups.emplace_back(resultIt, std::get<2>(record));
resultIt += std::get<1>(record);
}
state.asmState->finalizeOperationDefinition(
op, nameTok.getLocRange(), getLastToken().getEndLoc(),
asmResultGroups);
}
unsigned opResI = 0;
for (ResultRecord &resIt : resultIDs) {
for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) {
if (addDefinition({std::get<2>(resIt), std::get<0>(resIt), subRes},
op->getResult(opResI++)))
return failure();
}
}
} else if (state.asmState) {
state.asmState->finalizeOperationDefinition(
op, nameTok.getLocRange(),
getLastToken().getEndLoc());
}
return success();
}
ParseResult OperationParser::parseSuccessor(Block *&dest) {
if (getToken().isCodeCompletion())
return codeCompleteBlock();
if (!getToken().is(Token::caret_identifier))
return emitWrongTokenError("expected block name");
dest = getBlockNamed(getTokenSpelling(), getToken().getLoc());
consumeToken();
return success();
}
ParseResult
OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) {
if (parseToken(Token::l_square, "expected '['"))
return failure();
auto parseElt = [this, &destinations] {
Block *dest;
ParseResult res = parseSuccessor(dest);
destinations.push_back(dest);
return res;
};
return parseCommaSeparatedListUntil(Token::r_square, parseElt,
false);
}
namespace {
struct CleanupOpStateRegions {
~CleanupOpStateRegions() {
SmallVector<Region *, 4> regionsToClean;
regionsToClean.reserve(state.regions.size());
for (auto ®ion : state.regions)
if (region)
for (auto &block : *region)
block.dropAllDefinedValueUses();
}
OperationState &state;
};
}
ParseResult OperationParser::parseGenericOperationAfterOpName(
OperationState &result,
std::optional<ArrayRef<UnresolvedOperand>> parsedOperandUseInfo,
std::optional<ArrayRef<Block *>> parsedSuccessors,
std::optional<MutableArrayRef<std::unique_ptr<Region>>> parsedRegions,
std::optional<ArrayRef<NamedAttribute>> parsedAttributes,
std::optional<Attribute> propertiesAttribute,
std::optional<FunctionType> parsedFnType) {
SmallVector<UnresolvedOperand, 8> opInfo;
if (!parsedOperandUseInfo) {
if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
parseOptionalSSAUseList(opInfo) ||
parseToken(Token::r_paren, "expected ')' to end operand list")) {
return failure();
}
parsedOperandUseInfo = opInfo;
}
if (!parsedSuccessors) {
if (getToken().is(Token::l_square)) {
if (!result.name.mightHaveTrait<OpTrait::IsTerminator>())
return emitError("successors in non-terminator");
SmallVector<Block *, 2> successors;
if (parseSuccessors(successors))
return failure();
result.addSuccessors(successors);
}
} else {
result.addSuccessors(*parsedSuccessors);
}
if (propertiesAttribute) {
result.propertiesAttr = *propertiesAttribute;
} else if (consumeIf(Token::less)) {
result.propertiesAttr = parseAttribute();
if (!result.propertiesAttr)
return failure();
if (parseToken(Token::greater, "expected '>' to close properties"))
return failure();
}
if (!parsedRegions) {
if (consumeIf(Token::l_paren)) {
do {
result.regions.emplace_back(new Region(topLevelOp));
if (parseRegion(*result.regions.back(), {}))
return failure();
} while (consumeIf(Token::comma));
if (parseToken(Token::r_paren, "expected ')' to end region list"))
return failure();
}
} else {
result.addRegions(*parsedRegions);
}
if (!parsedAttributes) {
if (getToken().is(Token::l_brace)) {
if (parseAttributeDict(result.attributes))
return failure();
}
} else {
result.addAttributes(*parsedAttributes);
}
Location typeLoc = result.location;
if (!parsedFnType) {
if (parseToken(Token::colon, "expected ':' followed by operation type"))
return failure();
typeLoc = getEncodedSourceLocation(getToken().getLoc());
auto type = parseType();
if (!type)
return failure();
auto fnType = dyn_cast<FunctionType>(type);
if (!fnType)
return mlir::emitError(typeLoc, "expected function type");
parsedFnType = fnType;
}
result.addTypes(parsedFnType->getResults());
ArrayRef<Type> operandTypes = parsedFnType->getInputs();
if (operandTypes.size() != parsedOperandUseInfo->size()) {
auto plural = "s"[parsedOperandUseInfo->size() == 1];
return mlir::emitError(typeLoc, "expected ")
<< parsedOperandUseInfo->size() << " operand type" << plural
<< " but had " << operandTypes.size();
}
for (unsigned i = 0, e = parsedOperandUseInfo->size(); i != e; ++i) {
result.operands.push_back(
resolveSSAUse((*parsedOperandUseInfo)[i], operandTypes[i]));
if (!result.operands.back())
return failure();
}
return success();
}
Operation *OperationParser::parseGenericOperation() {
auto srcLocation = getEncodedSourceLocation(getToken().getLoc());
std::string name = getToken().getStringValue();
if (name.empty())
return (emitError("empty operation name is invalid"), nullptr);
if (name.find('\0') != StringRef::npos)
return (emitError("null character not allowed in operation name"), nullptr);
consumeToken(Token::string);
OperationState result(srcLocation, name);
CleanupOpStateRegions guard{result};
if (!result.name.isRegistered()) {
StringRef dialectName = StringRef(name).split('.').first;
if (!getContext()->getLoadedDialect(dialectName) &&
!getContext()->getOrLoadDialect(dialectName)) {
if (!getContext()->allowsUnregisteredDialects()) {
emitError("operation being parsed with an unregistered dialect. If "
"this is intended, please use -allow-unregistered-dialect "
"with the MLIR tool used");
return nullptr;
}
} else {
result.name = OperationName(name, getContext());
}
}
if (state.asmState)
state.asmState->startOperationDefinition(result.name);
if (parseGenericOperationAfterOpName(result))
return nullptr;
Attribute properties;
std::swap(properties, result.propertiesAttr);
if (!properties && !result.getRawProperties()) {
std::optional<RegisteredOperationName> info =
result.name.getRegisteredInfo();
if (info) {
if (failed(info->verifyInherentAttrs(result.attributes, [&]() {
return mlir::emitError(srcLocation) << "'" << name << "' op ";
})))
return nullptr;
}
}
Operation *op = opBuilder.create(result);
if (parseTrailingLocationSpecifier(op))
return nullptr;
if (properties) {
auto emitError = [&]() {
return mlir::emitError(srcLocation, "invalid properties ")
<< properties << " for op " << name << ": ";
};
if (failed(op->setPropertiesFromAttribute(properties, emitError)))
return nullptr;
}
return op;
}
Operation *OperationParser::parseGenericOperation(Block *insertBlock,
Block::iterator insertPt) {
Token nameToken = getToken();
OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
opBuilder.setInsertionPoint(insertBlock, insertPt);
Operation *op = parseGenericOperation();
if (!op)
return nullptr;
if (state.asmState)
state.asmState->finalizeOperationDefinition(
op, nameToken.getLocRange(),
getLastToken().getEndLoc());
return op;
}
namespace {
class CustomOpAsmParser : public AsmParserImpl<OpAsmParser> {
public:
CustomOpAsmParser(
SMLoc nameLoc, ArrayRef<OperationParser::ResultRecord> resultIDs,
function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly,
bool isIsolatedFromAbove, StringRef opName, OperationParser &parser)
: AsmParserImpl<OpAsmParser>(nameLoc, parser), resultIDs(resultIDs),
parseAssembly(parseAssembly), isIsolatedFromAbove(isIsolatedFromAbove),
opName(opName), parser(parser) {
(void)isIsolatedFromAbove;
}
ParseResult parseOperation(OperationState &opState) {
if (parseAssembly(*this, opState))
return failure();
std::optional<NamedAttribute> duplicate =
opState.attributes.findDuplicate();
if (duplicate)
return emitError(getNameLoc(), "attribute '")
<< duplicate->getName().getValue()
<< "' occurs more than once in the attribute list";
return success();
}
Operation *parseGenericOperation(Block *insertBlock,
Block::iterator insertPt) final {
return parser.parseGenericOperation(insertBlock, insertPt);
}
FailureOr<OperationName> parseCustomOperationName() final {
return parser.parseCustomOperationName();
}
ParseResult parseGenericOperationAfterOpName(
OperationState &result,
std::optional<ArrayRef<UnresolvedOperand>> parsedUnresolvedOperands,
std::optional<ArrayRef<Block *>> parsedSuccessors,
std::optional<MutableArrayRef<std::unique_ptr<Region>>> parsedRegions,
std::optional<ArrayRef<NamedAttribute>> parsedAttributes,
std::optional<Attribute> parsedPropertiesAttribute,
std::optional<FunctionType> parsedFnType) final {
return parser.parseGenericOperationAfterOpName(
result, parsedUnresolvedOperands, parsedSuccessors, parsedRegions,
parsedAttributes, parsedPropertiesAttribute, parsedFnType);
}
std::pair<StringRef, unsigned>
getResultName(unsigned resultNo) const override {
for (const auto &entry : resultIDs) {
if (resultNo < std::get<1>(entry)) {
StringRef name = std::get<0>(entry).drop_front();
return {name, resultNo};
}
resultNo -= std::get<1>(entry);
}
return {"", ~0U};
}
size_t getNumResults() const override {
size_t count = 0;
for (auto &entry : resultIDs)
count += std::get<1>(entry);
return count;
}
InFlightDiagnostic emitError(SMLoc loc, const Twine &message) override {
return AsmParserImpl<OpAsmParser>::emitError(loc, "custom op '" + opName +
"' " + message);
}
ParseResult parseOperand(UnresolvedOperand &result,
bool allowResultNumber = true) override {
OperationParser::UnresolvedOperand useInfo;
if (parser.parseSSAUse(useInfo, allowResultNumber))
return failure();
result = {useInfo.location, useInfo.name, useInfo.number};
return success();
}
OptionalParseResult
parseOptionalOperand(UnresolvedOperand &result,
bool allowResultNumber = true) override {
if (parser.getToken().isOrIsCodeCompletionFor(Token::percent_identifier))
return parseOperand(result, allowResultNumber);
return std::nullopt;
}
ParseResult parseOperandList(SmallVectorImpl<UnresolvedOperand> &result,
Delimiter delimiter = Delimiter::None,
bool allowResultNumber = true,
int requiredOperandCount = -1) override {
if (delimiter == Delimiter::None) {
Token tok = parser.getToken();
if (!tok.isOrIsCodeCompletionFor(Token::percent_identifier)) {
if (requiredOperandCount == -1 || requiredOperandCount == 0)
return success();
if (tok.isAny(Token::l_paren, Token::l_square))
return parser.emitError("unexpected delimiter");
return parser.emitWrongTokenError("expected operand");
}
}
auto parseOneOperand = [&]() -> ParseResult {
return parseOperand(result.emplace_back(), allowResultNumber);
};
auto startLoc = parser.getToken().getLoc();
if (parseCommaSeparatedList(delimiter, parseOneOperand, " in operand list"))
return failure();
if (requiredOperandCount != -1 &&
result.size() != static_cast<size_t>(requiredOperandCount))
return emitError(startLoc, "expected ")
<< requiredOperandCount << " operands";
return success();
}
ParseResult resolveOperand(const UnresolvedOperand &operand, Type type,
SmallVectorImpl<Value> &result) override {
if (auto value = parser.resolveSSAUse(operand, type)) {
result.push_back(value);
return success();
}
return failure();
}
ParseResult
parseAffineMapOfSSAIds(SmallVectorImpl<UnresolvedOperand> &operands,
Attribute &mapAttr, StringRef attrName,
NamedAttrList &attrs, Delimiter delimiter) override {
SmallVector<UnresolvedOperand, 2> dimOperands;
SmallVector<UnresolvedOperand, 1> symOperands;
auto parseElement = [&](bool isSymbol) -> ParseResult {
UnresolvedOperand operand;
if (parseOperand(operand))
return failure();
if (isSymbol)
symOperands.push_back(operand);
else
dimOperands.push_back(operand);
return success();
};
AffineMap map;
if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
return failure();
if (map) {
mapAttr = AffineMapAttr::get(map);
attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
}
operands.assign(dimOperands.begin(), dimOperands.end());
operands.append(symOperands.begin(), symOperands.end());
return success();
}
ParseResult
parseAffineExprOfSSAIds(SmallVectorImpl<UnresolvedOperand> &dimOperands,
SmallVectorImpl<UnresolvedOperand> &symbOperands,
AffineExpr &expr) override {
auto parseElement = [&](bool isSymbol) -> ParseResult {
UnresolvedOperand operand;
if (parseOperand(operand))
return failure();
if (isSymbol)
symbOperands.push_back(operand);
else
dimOperands.push_back(operand);
return success();
};
return parser.parseAffineExprOfSSAIds(expr, parseElement);
}
ParseResult parseArgument(Argument &result, bool allowType = false,
bool allowAttrs = false) override {
NamedAttrList attrs;
if (parseOperand(result.ssaName, false) ||
(allowType && parseColonType(result.type)) ||
(allowAttrs && parseOptionalAttrDict(attrs)) ||
parseOptionalLocationSpecifier(result.sourceLoc))
return failure();
result.attrs = attrs.getDictionary(getContext());
return success();
}
OptionalParseResult parseOptionalArgument(Argument &result, bool allowType,
bool allowAttrs) override {
if (parser.getToken().is(Token::percent_identifier))
return parseArgument(result, allowType, allowAttrs);
return std::nullopt;
}
ParseResult parseArgumentList(SmallVectorImpl<Argument> &result,
Delimiter delimiter, bool allowType,
bool allowAttrs) override {
if (delimiter == Delimiter::None &&
parser.getToken().isNot(Token::percent_identifier))
return success();
auto parseOneArgument = [&]() -> ParseResult {
return parseArgument(result.emplace_back(), allowType, allowAttrs);
};
return parseCommaSeparatedList(delimiter, parseOneArgument,
" in argument list");
}
ParseResult parseRegion(Region ®ion, ArrayRef<Argument> arguments,
bool enableNameShadowing) override {
(void)isIsolatedFromAbove;
assert((!enableNameShadowing || isIsolatedFromAbove) &&
"name shadowing is only allowed on isolated regions");
if (parser.parseRegion(region, arguments, enableNameShadowing))
return failure();
return success();
}
OptionalParseResult parseOptionalRegion(Region ®ion,
ArrayRef<Argument> arguments,
bool enableNameShadowing) override {
if (parser.getToken().isNot(Token::l_brace))
return std::nullopt;
return parseRegion(region, arguments, enableNameShadowing);
}
OptionalParseResult
parseOptionalRegion(std::unique_ptr<Region> ®ion,
ArrayRef<Argument> arguments,
bool enableNameShadowing = false) override {
if (parser.getToken().isNot(Token::l_brace))
return std::nullopt;
std::unique_ptr<Region> newRegion = std::make_unique<Region>();
if (parseRegion(*newRegion, arguments, enableNameShadowing))
return failure();
region = std::move(newRegion);
return success();
}
ParseResult parseSuccessor(Block *&dest) override {
return parser.parseSuccessor(dest);
}
OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
if (!parser.getToken().isOrIsCodeCompletionFor(Token::caret_identifier))
return std::nullopt;
return parseSuccessor(dest);
}
ParseResult
parseSuccessorAndUseList(Block *&dest,
SmallVectorImpl<Value> &operands) override {
if (parseSuccessor(dest))
return failure();
if (succeeded(parseOptionalLParen()) &&
(parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
return failure();
}
return success();
}
OptionalParseResult parseOptionalAssignmentList(
SmallVectorImpl<Argument> &lhs,
SmallVectorImpl<UnresolvedOperand> &rhs) override {
if (failed(parseOptionalLParen()))
return std::nullopt;
auto parseElt = [&]() -> ParseResult {
if (parseArgument(lhs.emplace_back()) || parseEqual() ||
parseOperand(rhs.emplace_back()))
return failure();
return success();
};
return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
}
ParseResult
parseOptionalLocationSpecifier(std::optional<Location> &result) override {
if (!parser.consumeIf(Token::kw_loc))
return success();
LocationAttr directLoc;
if (parser.parseToken(Token::l_paren, "expected '(' in location"))
return failure();
Token tok = parser.getToken();
if (tok.is(Token::hash_identifier)) {
if (parser.parseLocationAlias(directLoc))
return failure();
} else if (parser.parseLocationInstance(directLoc)) {
return failure();
}
if (parser.parseToken(Token::r_paren, "expected ')' in location"))
return failure();
result = directLoc;
return success();
}
private:
ArrayRef<OperationParser::ResultRecord> resultIDs;
function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly;
bool isIsolatedFromAbove;
StringRef opName;
OperationParser &parser;
};
}
FailureOr<OperationName> OperationParser::parseCustomOperationName() {
Token nameTok = getToken();
StringRef opName = nameTok.getSpelling();
if (opName.empty())
return (emitError("empty operation name is invalid"), failure());
consumeToken();
std::optional<RegisteredOperationName> opInfo =
RegisteredOperationName::lookup(opName, getContext());
if (opInfo)
return *opInfo;
auto opNameSplit = opName.split('.');
StringRef dialectName = opNameSplit.first;
std::string opNameStorage;
if (opNameSplit.second.empty()) {
if (getToken().isCodeCompletion() && opName.back() == '.')
return codeCompleteOperationName(dialectName);
dialectName = getState().defaultDialectStack.back();
opNameStorage = (dialectName + "." + opName).str();
opName = opNameStorage;
}
getContext()->getOrLoadDialect(dialectName);
return OperationName(opName, getContext());
}
Operation *
OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) {
SMLoc opLoc = getToken().getLoc();
StringRef originalOpName = getTokenSpelling();
FailureOr<OperationName> opNameInfo = parseCustomOperationName();
if (failed(opNameInfo))
return nullptr;
StringRef opName = opNameInfo->getStringRef();
OperationName::ParseAssemblyFn parseAssemblyFn;
bool isIsolatedFromAbove = false;
StringRef defaultDialect = "";
if (auto opInfo = opNameInfo->getRegisteredInfo()) {
parseAssemblyFn = opInfo->getParseAssemblyFn();
isIsolatedFromAbove = opInfo->hasTrait<OpTrait::IsIsolatedFromAbove>();
auto *iface = opInfo->getInterface<OpAsmOpInterface>();
if (iface && !iface->getDefaultDialect().empty())
defaultDialect = iface->getDefaultDialect();
} else {
std::optional<Dialect::ParseOpHook> dialectHook;
Dialect *dialect = opNameInfo->getDialect();
if (!dialect) {
InFlightDiagnostic diag =
emitError(opLoc) << "Dialect `" << opNameInfo->getDialectNamespace()
<< "' not found for custom op '" << originalOpName
<< "' ";
if (originalOpName != opName)
diag << " (tried '" << opName << "' as well)";
auto ¬e = diag.attachNote();
note << "Registered dialects: ";
llvm::interleaveComma(getContext()->getAvailableDialects(), note,
[&](StringRef dialect) { note << dialect; });
note << " ; for more info on dialect registration see "
"https://mlir.llvm.org/getting_started/Faq/"
"#registered-loaded-dependent-whats-up-with-dialects-management";
return nullptr;
}
dialectHook = dialect->getParseOperationHook(opName);
if (!dialectHook) {
InFlightDiagnostic diag =
emitError(opLoc) << "custom op '" << originalOpName << "' is unknown";
if (originalOpName != opName)
diag << " (tried '" << opName << "' as well)";
return nullptr;
}
parseAssemblyFn = *dialectHook;
}
getState().defaultDialectStack.push_back(defaultDialect);
auto restoreDefaultDialect = llvm::make_scope_exit(
[&]() { getState().defaultDialectStack.pop_back(); });
llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
opNameInfo->getIdentifier().data());
auto srcLocation = getEncodedSourceLocation(opLoc);
OperationState opState(srcLocation, *opNameInfo);
if (state.asmState)
state.asmState->startOperationDefinition(opState.name);
CleanupOpStateRegions guard{opState};
CustomOpAsmParser opAsmParser(opLoc, resultIDs, parseAssemblyFn,
isIsolatedFromAbove, opName, *this);
if (opAsmParser.parseOperation(opState))
return nullptr;
if (opAsmParser.didEmitError())
return nullptr;
Attribute properties = opState.propertiesAttr;
opState.propertiesAttr = Attribute{};
Operation *op = opBuilder.create(opState);
if (parseTrailingLocationSpecifier(op))
return nullptr;
if (properties) {
auto emitError = [&]() {
return mlir::emitError(srcLocation, "invalid properties ")
<< properties << " for op " << op->getName().getStringRef()
<< ": ";
};
if (failed(op->setPropertiesFromAttribute(properties, emitError)))
return nullptr;
}
return op;
}
ParseResult OperationParser::parseLocationAlias(LocationAttr &loc) {
Token tok = getToken();
consumeToken(Token::hash_identifier);
StringRef identifier = tok.getSpelling().drop_front();
if (identifier.contains('.')) {
return emitError(tok.getLoc())
<< "expected location, but found dialect attribute: '#" << identifier
<< "'";
}
if (state.asmState)
state.asmState->addAttrAliasUses(identifier, tok.getLocRange());
Attribute attr = state.symbols.attributeAliasDefinitions.lookup(identifier);
if (attr) {
if (!(loc = dyn_cast<LocationAttr>(attr)))
return emitError(tok.getLoc())
<< "expected location, but found '" << attr << "'";
} else {
loc = OpaqueLoc::get(deferredLocsReferences.size(),
TypeID::get<DeferredLocInfo *>(),
UnknownLoc::get(getContext()));
deferredLocsReferences.push_back(DeferredLocInfo{tok.getLoc(), identifier});
}
return success();
}
ParseResult
OperationParser::parseTrailingLocationSpecifier(OpOrArgument opOrArgument) {
if (!consumeIf(Token::kw_loc))
return success();
if (parseToken(Token::l_paren, "expected '(' in location"))
return failure();
Token tok = getToken();
LocationAttr directLoc;
if (tok.is(Token::hash_identifier)) {
if (parseLocationAlias(directLoc))
return failure();
} else if (parseLocationInstance(directLoc)) {
return failure();
}
if (parseToken(Token::r_paren, "expected ')' in location"))
return failure();
if (auto *op = llvm::dyn_cast_if_present<Operation *>(opOrArgument))
op->setLoc(directLoc);
else
opOrArgument.get<BlockArgument>().setLoc(directLoc);
return success();
}
ParseResult OperationParser::parseRegion(Region ®ion,
ArrayRef<Argument> entryArguments,
bool isIsolatedNameScope) {
Token lBraceTok = getToken();
if (parseToken(Token::l_brace, "expected '{' to begin a region"))
return failure();
if (state.asmState)
state.asmState->startRegionDefinition();
if ((!entryArguments.empty() || getToken().isNot(Token::r_brace)) &&
parseRegionBody(region, lBraceTok.getLoc(), entryArguments,
isIsolatedNameScope)) {
return failure();
}
consumeToken(Token::r_brace);
if (state.asmState)
state.asmState->finalizeRegionDefinition();
return success();
}
ParseResult OperationParser::parseRegionBody(Region ®ion, SMLoc startLoc,
ArrayRef<Argument> entryArguments,
bool isIsolatedNameScope) {
auto currentPt = opBuilder.saveInsertionPoint();
pushSSANameScope(isIsolatedNameScope);
auto owningBlock = std::make_unique<Block>();
Block *block = owningBlock.get();
if (state.asmState && getToken().isNot(Token::caret_identifier))
state.asmState->addDefinition(block, startLoc);
if (!entryArguments.empty() && !entryArguments[0].ssaName.name.empty()) {
if (getToken().is(Token::caret_identifier))
return emitError("invalid block name in region with named arguments");
for (auto &entryArg : entryArguments) {
auto &argInfo = entryArg.ssaName;
if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
return emitError(argInfo.location, "region entry argument '" +
argInfo.name +
"' is already in use")
.attachNote(getEncodedSourceLocation(*defLoc))
<< "previously referenced here";
}
Location loc = entryArg.sourceLoc.has_value()
? *entryArg.sourceLoc
: getEncodedSourceLocation(argInfo.location);
BlockArgument arg = block->addArgument(entryArg.type, loc);
if (state.asmState)
state.asmState->addDefinition(arg, argInfo.location);
if (addDefinition(argInfo, arg))
return failure();
}
}
if (parseBlock(block))
return failure();
if (!entryArguments.empty() &&
block->getNumArguments() > entryArguments.size()) {
return emitError("entry block arguments were already defined");
}
region.push_back(owningBlock.release());
while (getToken().isNot(Token::r_brace)) {
Block *newBlock = nullptr;
if (parseBlock(newBlock))
return failure();
region.push_back(newBlock);
}
if (popSSANameScope())
return failure();
opBuilder.restoreInsertionPoint(currentPt);
return success();
}
ParseResult OperationParser::parseBlock(Block *&block) {
if (block && getToken().isNot(Token::caret_identifier))
return parseBlockBody(block);
SMLoc nameLoc = getToken().getLoc();
auto name = getTokenSpelling();
if (parseToken(Token::caret_identifier, "expected block name"))
return failure();
auto &blockAndLoc = getBlockInfoByName(name);
blockAndLoc.loc = nameLoc;
std::unique_ptr<Block> inflightBlock;
auto cleanupOnFailure = llvm::make_scope_exit([&] {
if (inflightBlock)
inflightBlock->dropAllDefinedValueUses();
});
if (!blockAndLoc.block) {
if (block) {
blockAndLoc.block = block;
} else {
inflightBlock = std::make_unique<Block>();
blockAndLoc.block = inflightBlock.get();
}
} else if (!eraseForwardRef(blockAndLoc.block)) {
return emitError(nameLoc, "redefinition of block '") << name << "'";
} else {
inflightBlock.reset(blockAndLoc.block);
}
if (state.asmState)
state.asmState->addDefinition(blockAndLoc.block, nameLoc);
block = blockAndLoc.block;
if (getToken().is(Token::l_paren))
if (parseOptionalBlockArgList(block))
return failure();
if (parseToken(Token::colon, "expected ':' after block name"))
return failure();
ParseResult res = parseBlockBody(block);
if (succeeded(res))
(void)inflightBlock.release();
return res;
}
ParseResult OperationParser::parseBlockBody(Block *block) {
opBuilder.setInsertionPointToEnd(block);
while (getToken().isNot(Token::caret_identifier, Token::r_brace))
if (parseOperation())
return failure();
return success();
}
Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
BlockDefinition &blockDef = getBlockInfoByName(name);
if (!blockDef.block) {
blockDef = {new Block(), loc};
insertForwardRef(blockDef.block, blockDef.loc);
}
if (state.asmState)
state.asmState->addUses(blockDef.block, loc);
return blockDef.block;
}
ParseResult OperationParser::parseOptionalBlockArgList(Block *owner) {
if (getToken().is(Token::r_brace))
return success();
bool definingExistingArgs = owner->getNumArguments() != 0;
unsigned nextArgument = 0;
return parseCommaSeparatedList(Delimiter::Paren, [&]() -> ParseResult {
return parseSSADefOrUseAndType(
[&](UnresolvedOperand useInfo, Type type) -> ParseResult {
BlockArgument arg;
if (definingExistingArgs) {
if (nextArgument >= owner->getNumArguments())
return emitError("too many arguments specified in argument list");
arg = owner->getArgument(nextArgument++);
if (arg.getType() != type)
return emitError("argument and block argument type mismatch");
} else {
auto loc = getEncodedSourceLocation(useInfo.location);
arg = owner->addArgument(type, loc);
}
if (parseTrailingLocationSpecifier(arg))
return failure();
if (state.asmState)
state.asmState->addDefinition(arg, useInfo.location);
return addDefinition(useInfo, arg);
});
});
}
ParseResult OperationParser::codeCompleteSSAUse() {
std::string detailData;
llvm::raw_string_ostream detailOS(detailData);
for (IsolatedSSANameScope &scope : isolatedNameScopes) {
for (auto &it : scope.values) {
if (it.second.empty())
continue;
Value frontValue = it.second.front().value;
if (auto result = dyn_cast<OpResult>(frontValue)) {
if (!forwardRefPlaceholders.count(result))
detailOS << result.getOwner()->getName() << ": ";
} else {
detailOS << "arg #" << cast<BlockArgument>(frontValue).getArgNumber()
<< ": ";
}
detailOS << frontValue.getType();
if (it.second.size() > 1)
detailOS << ", ...";
state.codeCompleteContext->appendSSAValueCompletion(
it.getKey(), std::move(detailOS.str()));
}
}
return failure();
}
ParseResult OperationParser::codeCompleteBlock() {
StringRef spelling = getTokenSpelling();
if (!(spelling.empty() || spelling == "^"))
return failure();
for (const auto &it : blocksByName.back())
state.codeCompleteContext->appendBlockCompletion(it.getFirst());
return failure();
}
namespace {
class TopLevelOperationParser : public Parser {
public:
explicit TopLevelOperationParser(ParserState &state) : Parser(state) {}
ParseResult parse(Block *topLevelBlock, Location parserLoc);
private:
ParseResult parseAttributeAliasDef();
ParseResult parseTypeAliasDef();
ParseResult parseFileMetadataDictionary();
ParseResult parseResourceFileMetadata(
function_ref<ParseResult(StringRef, SMLoc)> parseBody);
ParseResult parseDialectResourceFileMetadata();
ParseResult parseExternalResourceFileMetadata();
};
class ParsedResourceEntry : public AsmParsedResourceEntry {
public:
ParsedResourceEntry(StringRef key, SMLoc keyLoc, Token value, Parser &p)
: key(key), keyLoc(keyLoc), value(value), p(p) {}
~ParsedResourceEntry() override = default;
StringRef getKey() const final { return key; }
InFlightDiagnostic emitError() const final { return p.emitError(keyLoc); }
AsmResourceEntryKind getKind() const final {
if (value.isAny(Token::kw_true, Token::kw_false))
return AsmResourceEntryKind::Bool;
return value.getSpelling().starts_with("\"0x")
? AsmResourceEntryKind::Blob
: AsmResourceEntryKind::String;
}
FailureOr<bool> parseAsBool() const final {
if (value.is(Token::kw_true))
return true;
if (value.is(Token::kw_false))
return false;
return p.emitError(value.getLoc(),
"expected 'true' or 'false' value for key '" + key +
"'");
}
FailureOr<std::string> parseAsString() const final {
if (value.isNot(Token::string))
return p.emitError(value.getLoc(),
"expected string value for key '" + key + "'");
return value.getStringValue();
}
FailureOr<AsmResourceBlob>
parseAsBlob(BlobAllocatorFn allocator) const final {
std::optional<std::string> blobData =
value.is(Token::string) ? value.getHexStringValue() : std::nullopt;
if (!blobData)
return p.emitError(value.getLoc(),
"expected hex string blob for key '" + key + "'");
if (blobData->size() < sizeof(uint32_t)) {
return p.emitError(value.getLoc(),
"expected hex string blob for key '" + key +
"' to encode alignment in first 4 bytes");
}
llvm::support::ulittle32_t align;
memcpy(&align, blobData->data(), sizeof(uint32_t));
if (align && !llvm::isPowerOf2_32(align)) {
return p.emitError(value.getLoc(),
"expected hex string blob for key '" + key +
"' to encode alignment in first 4 bytes, but got "
"non-power-of-2 value: " +
Twine(align));
}
StringRef data = StringRef(*blobData).drop_front(sizeof(uint32_t));
if (data.empty())
return AsmResourceBlob();
AsmResourceBlob blob = allocator(data.size(), align);
assert(llvm::isAddrAligned(llvm::Align(align), blob.getData().data()) &&
blob.isMutable() &&
"blob allocator did not return a properly aligned address");
memcpy(blob.getMutableData().data(), data.data(), data.size());
return blob;
}
private:
StringRef key;
SMLoc keyLoc;
Token value;
Parser &p;
};
}
ParseResult TopLevelOperationParser::parseAttributeAliasDef() {
assert(getToken().is(Token::hash_identifier));
StringRef aliasName = getTokenSpelling().drop_front();
if (state.symbols.attributeAliasDefinitions.count(aliasName) > 0)
return emitError("redefinition of attribute alias id '" + aliasName + "'");
if (aliasName.contains('.'))
return emitError("attribute names with a '.' are reserved for "
"dialect-defined names");
SMRange location = getToken().getLocRange();
consumeToken(Token::hash_identifier);
if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
return failure();
Attribute attr = parseAttribute();
if (!attr)
return failure();
if (state.asmState)
state.asmState->addAttrAliasDefinition(aliasName, location, attr);
state.symbols.attributeAliasDefinitions[aliasName] = attr;
return success();
}
ParseResult TopLevelOperationParser::parseTypeAliasDef() {
assert(getToken().is(Token::exclamation_identifier));
StringRef aliasName = getTokenSpelling().drop_front();
if (state.symbols.typeAliasDefinitions.count(aliasName) > 0)
return emitError("redefinition of type alias id '" + aliasName + "'");
if (aliasName.contains('.'))
return emitError("type names with a '.' are reserved for "
"dialect-defined names");
SMRange location = getToken().getLocRange();
consumeToken(Token::exclamation_identifier);
if (parseToken(Token::equal, "expected '=' in type alias definition"))
return failure();
Type aliasedType = parseType();
if (!aliasedType)
return failure();
if (state.asmState)
state.asmState->addTypeAliasDefinition(aliasName, location, aliasedType);
state.symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
return success();
}
ParseResult TopLevelOperationParser::parseFileMetadataDictionary() {
consumeToken(Token::file_metadata_begin);
return parseCommaSeparatedListUntil(
Token::file_metadata_end, [&]() -> ParseResult {
SMLoc keyLoc = getToken().getLoc();
StringRef key;
if (failed(parseOptionalKeyword(&key)))
return emitError("expected identifier key in file "
"metadata dictionary");
if (parseToken(Token::colon, "expected ':'"))
return failure();
if (key == "dialect_resources")
return parseDialectResourceFileMetadata();
if (key == "external_resources")
return parseExternalResourceFileMetadata();
return emitError(keyLoc, "unknown key '" + key +
"' in file metadata dictionary");
});
}
ParseResult TopLevelOperationParser::parseResourceFileMetadata(
function_ref<ParseResult(StringRef, SMLoc)> parseBody) {
if (parseToken(Token::l_brace, "expected '{'"))
return failure();
return parseCommaSeparatedListUntil(Token::r_brace, [&]() -> ParseResult {
SMLoc nameLoc = getToken().getLoc();
StringRef name;
if (failed(parseOptionalKeyword(&name)))
return emitError("expected identifier key for 'resource' entry");
if (parseToken(Token::colon, "expected ':'") ||
parseToken(Token::l_brace, "expected '{'"))
return failure();
return parseBody(name, nameLoc);
});
}
ParseResult TopLevelOperationParser::parseDialectResourceFileMetadata() {
return parseResourceFileMetadata([&](StringRef name,
SMLoc nameLoc) -> ParseResult {
Dialect *dialect = getContext()->getOrLoadDialect(name);
if (!dialect)
return emitError(nameLoc, "dialect '" + name + "' is unknown");
const auto *handler = dyn_cast<OpAsmDialectInterface>(dialect);
if (!handler) {
return emitError() << "unexpected 'resource' section for dialect '"
<< dialect->getNamespace() << "'";
}
return parseCommaSeparatedListUntil(Token::r_brace, [&]() -> ParseResult {
SMLoc keyLoc = getToken().getLoc();
StringRef key;
if (failed(parseResourceHandle(handler, key)) ||
parseToken(Token::colon, "expected ':'"))
return failure();
Token valueTok = getToken();
consumeToken();
ParsedResourceEntry entry(key, keyLoc, valueTok, *this);
return handler->parseResource(entry);
});
});
}
ParseResult TopLevelOperationParser::parseExternalResourceFileMetadata() {
return parseResourceFileMetadata([&](StringRef name,
SMLoc nameLoc) -> ParseResult {
AsmResourceParser *handler = state.config.getResourceParser(name);
if (!handler) {
emitWarning(getEncodedSourceLocation(nameLoc))
<< "ignoring unknown external resources for '" << name << "'";
}
return parseCommaSeparatedListUntil(Token::r_brace, [&]() -> ParseResult {
SMLoc keyLoc = getToken().getLoc();
StringRef key;
if (failed(parseOptionalKeyword(&key)))
return emitError(
"expected identifier key for 'external_resources' entry");
if (parseToken(Token::colon, "expected ':'"))
return failure();
Token valueTok = getToken();
consumeToken();
if (!handler)
return success();
ParsedResourceEntry entry(key, keyLoc, valueTok, *this);
return handler->parseResource(entry);
});
});
}
ParseResult TopLevelOperationParser::parse(Block *topLevelBlock,
Location parserLoc) {
OwningOpRef<ModuleOp> topLevelOp(ModuleOp::create(parserLoc));
OperationParser opParser(state, topLevelOp.get());
while (true) {
switch (getToken().getKind()) {
default:
if (opParser.parseOperation())
return failure();
break;
case Token::eof: {
if (opParser.finalize())
return failure();
auto &parsedOps = topLevelOp->getBody()->getOperations();
auto &destOps = topLevelBlock->getOperations();
destOps.splice(destOps.end(), parsedOps, parsedOps.begin(),
parsedOps.end());
return success();
}
case Token::error:
return failure();
case Token::hash_identifier:
if (parseAttributeAliasDef())
return failure();
break;
case Token::exclamation_identifier:
if (parseTypeAliasDef())
return failure();
break;
case Token::file_metadata_begin:
if (parseFileMetadataDictionary())
return failure();
break;
}
}
}
LogicalResult
mlir::parseAsmSourceFile(const llvm::SourceMgr &sourceMgr, Block *block,
const ParserConfig &config, AsmParserState *asmState,
AsmParserCodeCompleteContext *codeCompleteContext) {
const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
Location parserLoc =
FileLineColLoc::get(config.getContext(), sourceBuf->getBufferIdentifier(),
0, 0);
SymbolState aliasState;
ParserState state(sourceMgr, config, aliasState, asmState,
codeCompleteContext);
return TopLevelOperationParser(state).parse(block, parserLoc);
}