1 //===- Parser.cpp - MLIR Parser Implementation ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the parser for the MLIR textual form. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "Parser.h" 14 #include "mlir/IR/AffineMap.h" 15 #include "mlir/IR/BuiltinOps.h" 16 #include "mlir/IR/Dialect.h" 17 #include "mlir/IR/Verifier.h" 18 #include "mlir/Parser.h" 19 #include "mlir/Parser/AsmParserState.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/StringSet.h" 22 #include "llvm/ADT/bit.h" 23 #include "llvm/Support/PrettyStackTrace.h" 24 #include "llvm/Support/SourceMgr.h" 25 #include <algorithm> 26 27 using namespace mlir; 28 using namespace mlir::detail; 29 using llvm::MemoryBuffer; 30 using llvm::SMLoc; 31 using llvm::SourceMgr; 32 33 //===----------------------------------------------------------------------===// 34 // Parser 35 //===----------------------------------------------------------------------===// 36 37 /// Parse a comma separated list of elements that must have at least one entry 38 /// in it. 39 ParseResult 40 Parser::parseCommaSeparatedList(function_ref<ParseResult()> parseElement) { 41 // Non-empty case starts with an element. 42 if (parseElement()) 43 return failure(); 44 45 // Otherwise we have a list of comma separated elements. 46 while (consumeIf(Token::comma)) { 47 if (parseElement()) 48 return failure(); 49 } 50 return success(); 51 } 52 53 /// Parse a comma-separated list of elements, terminated with an arbitrary 54 /// token. This allows empty lists if allowEmptyList is true. 55 /// 56 /// abstract-list ::= rightToken // if allowEmptyList == true 57 /// abstract-list ::= element (',' element)* rightToken 58 /// 59 ParseResult 60 Parser::parseCommaSeparatedListUntil(Token::Kind rightToken, 61 function_ref<ParseResult()> parseElement, 62 bool allowEmptyList) { 63 // Handle the empty case. 64 if (getToken().is(rightToken)) { 65 if (!allowEmptyList) 66 return emitError("expected list element"); 67 consumeToken(rightToken); 68 return success(); 69 } 70 71 if (parseCommaSeparatedList(parseElement) || 72 parseToken(rightToken, "expected ',' or '" + 73 Token::getTokenSpelling(rightToken) + "'")) 74 return failure(); 75 76 return success(); 77 } 78 79 InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) { 80 auto diag = mlir::emitError(getEncodedSourceLocation(loc), message); 81 82 // If we hit a parse error in response to a lexer error, then the lexer 83 // already reported the error. 84 if (getToken().is(Token::error)) 85 diag.abandon(); 86 return diag; 87 } 88 89 /// Consume the specified token if present and return success. On failure, 90 /// output a diagnostic and return failure. 91 ParseResult Parser::parseToken(Token::Kind expectedToken, 92 const Twine &message) { 93 if (consumeIf(expectedToken)) 94 return success(); 95 return emitError(message); 96 } 97 98 /// Parse an optional integer value from the stream. 99 OptionalParseResult Parser::parseOptionalInteger(uint64_t &result) { 100 Token curToken = getToken(); 101 if (curToken.isNot(Token::integer, Token::minus)) 102 return llvm::None; 103 104 bool negative = consumeIf(Token::minus); 105 Token curTok = getToken(); 106 if (parseToken(Token::integer, "expected integer value")) 107 return failure(); 108 109 auto val = curTok.getUInt64IntegerValue(); 110 if (!val) 111 return emitError(curTok.getLoc(), "integer value too large"); 112 result = negative ? -*val : *val; 113 return success(); 114 } 115 116 /// Parse a floating point value from an integer literal token. 117 ParseResult Parser::parseFloatFromIntegerLiteral( 118 Optional<APFloat> &result, const Token &tok, bool isNegative, 119 const llvm::fltSemantics &semantics, size_t typeSizeInBits) { 120 llvm::SMLoc loc = tok.getLoc(); 121 StringRef spelling = tok.getSpelling(); 122 bool isHex = spelling.size() > 1 && spelling[1] == 'x'; 123 if (!isHex) { 124 return emitError(loc, "unexpected decimal integer literal for a " 125 "floating point value") 126 .attachNote() 127 << "add a trailing dot to make the literal a float"; 128 } 129 if (isNegative) { 130 return emitError(loc, "hexadecimal float literal should not have a " 131 "leading minus"); 132 } 133 134 Optional<uint64_t> value = tok.getUInt64IntegerValue(); 135 if (!value.hasValue()) 136 return emitError(loc, "hexadecimal float constant out of range for type"); 137 138 if (&semantics == &APFloat::IEEEdouble()) { 139 result = APFloat(semantics, APInt(typeSizeInBits, *value)); 140 return success(); 141 } 142 143 APInt apInt(typeSizeInBits, *value); 144 if (apInt != *value) 145 return emitError(loc, "hexadecimal float constant out of range for type"); 146 result = APFloat(semantics, apInt); 147 148 return success(); 149 } 150 151 //===----------------------------------------------------------------------===// 152 // OperationParser 153 //===----------------------------------------------------------------------===// 154 155 namespace { 156 /// This class provides support for parsing operations and regions of 157 /// operations. 158 class OperationParser : public Parser { 159 public: 160 OperationParser(ParserState &state, Operation *topLevelOp) 161 : Parser(state), opBuilder(topLevelOp->getRegion(0)), 162 topLevelOp(topLevelOp) { 163 // The top level operation starts a new name scope. 164 pushSSANameScope(/*isIsolated=*/true); 165 } 166 167 ~OperationParser(); 168 169 /// After parsing is finished, this function must be called to see if there 170 /// are any remaining issues. 171 ParseResult finalize(); 172 173 //===--------------------------------------------------------------------===// 174 // SSA Value Handling 175 //===--------------------------------------------------------------------===// 176 177 /// This represents a use of an SSA value in the program. The first two 178 /// entries in the tuple are the name and result number of a reference. The 179 /// third is the location of the reference, which is used in case this ends 180 /// up being a use of an undefined value. 181 struct SSAUseInfo { 182 StringRef name; // Value name, e.g. %42 or %abc 183 unsigned number; // Number, specified with #12 184 SMLoc loc; // Location of first definition or use. 185 }; 186 187 /// Push a new SSA name scope to the parser. 188 void pushSSANameScope(bool isIsolated); 189 190 /// Pop the last SSA name scope from the parser. 191 ParseResult popSSANameScope(); 192 193 /// Register a definition of a value with the symbol table. 194 ParseResult addDefinition(SSAUseInfo useInfo, Value value); 195 196 /// Parse an optional list of SSA uses into 'results'. 197 ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results); 198 199 /// Parse a single SSA use into 'result'. 200 ParseResult parseSSAUse(SSAUseInfo &result); 201 202 /// Given a reference to an SSA value and its type, return a reference. This 203 /// returns null on failure. 204 Value resolveSSAUse(SSAUseInfo useInfo, Type type); 205 206 ParseResult 207 parseSSADefOrUseAndType(function_ref<ParseResult(SSAUseInfo, Type)> action); 208 209 ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results); 210 211 /// Return the location of the value identified by its name and number if it 212 /// has been already reference. 213 Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) { 214 auto &values = isolatedNameScopes.back().values; 215 if (!values.count(name) || number >= values[name].size()) 216 return {}; 217 if (values[name][number].value) 218 return values[name][number].loc; 219 return {}; 220 } 221 222 //===--------------------------------------------------------------------===// 223 // Operation Parsing 224 //===--------------------------------------------------------------------===// 225 226 /// Parse an operation instance. 227 ParseResult parseOperation(); 228 229 /// Parse a single operation successor. 230 ParseResult parseSuccessor(Block *&dest); 231 232 /// Parse a comma-separated list of operation successors in brackets. 233 ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations); 234 235 /// Parse an operation instance that is in the generic form. 236 Operation *parseGenericOperation(); 237 238 /// Parse an operation instance that is in the generic form and insert it at 239 /// the provided insertion point. 240 Operation *parseGenericOperation(Block *insertBlock, 241 Block::iterator insertPt); 242 243 /// Parse an optional trailing location for the given operation. 244 /// 245 /// trailing-location ::= (`loc` (`(` location `)` | attribute-alias))? 246 /// 247 ParseResult parseTrailingOperationLocation(Operation *op); 248 249 /// This is the structure of a result specifier in the assembly syntax, 250 /// including the name, number of results, and location. 251 using ResultRecord = std::tuple<StringRef, unsigned, SMLoc>; 252 253 /// Parse an operation instance that is in the op-defined custom form. 254 /// resultInfo specifies information about the "%name =" specifiers. 255 Operation *parseCustomOperation(ArrayRef<ResultRecord> resultIDs); 256 257 //===--------------------------------------------------------------------===// 258 // Region Parsing 259 //===--------------------------------------------------------------------===// 260 261 /// Parse a region into 'region' with the provided entry block arguments. 262 /// 'isIsolatedNameScope' indicates if the naming scope of this region is 263 /// isolated from those above. 264 ParseResult parseRegion(Region ®ion, 265 ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments, 266 bool isIsolatedNameScope = false); 267 268 /// Parse a region body into 'region'. 269 ParseResult parseRegionBody(Region ®ion); 270 271 //===--------------------------------------------------------------------===// 272 // Block Parsing 273 //===--------------------------------------------------------------------===// 274 275 /// Parse a new block into 'block'. 276 ParseResult parseBlock(Block *&block); 277 278 /// Parse a list of operations into 'block'. 279 ParseResult parseBlockBody(Block *block); 280 281 /// Parse a (possibly empty) list of block arguments. 282 ParseResult parseOptionalBlockArgList(Block *owner); 283 284 /// Get the block with the specified name, creating it if it doesn't 285 /// already exist. The location specified is the point of use, which allows 286 /// us to diagnose references to blocks that are not defined precisely. 287 Block *getBlockNamed(StringRef name, SMLoc loc); 288 289 /// Define the block with the specified name. Returns the Block* or nullptr in 290 /// the case of redefinition. 291 Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing); 292 293 private: 294 /// This class represents a definition of a Block. 295 struct BlockDefinition { 296 /// A pointer to the defined Block. 297 Block *block; 298 /// The location that the Block was defined at. 299 SMLoc loc; 300 }; 301 /// This class represents a definition of a Value. 302 struct ValueDefinition { 303 /// A pointer to the defined Value. 304 Value value; 305 /// The location that the Value was defined at. 306 SMLoc loc; 307 }; 308 309 /// Returns the info for a block at the current scope for the given name. 310 BlockDefinition &getBlockInfoByName(StringRef name) { 311 return blocksByName.back()[name]; 312 } 313 314 /// Insert a new forward reference to the given block. 315 void insertForwardRef(Block *block, SMLoc loc) { 316 forwardRef.back().try_emplace(block, loc); 317 } 318 319 /// Erase any forward reference to the given block. 320 bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); } 321 322 /// Record that a definition was added at the current scope. 323 void recordDefinition(StringRef def); 324 325 /// Get the value entry for the given SSA name. 326 SmallVectorImpl<ValueDefinition> &getSSAValueEntry(StringRef name); 327 328 /// Create a forward reference placeholder value with the given location and 329 /// result type. 330 Value createForwardRefPlaceholder(SMLoc loc, Type type); 331 332 /// Return true if this is a forward reference. 333 bool isForwardRefPlaceholder(Value value) { 334 return forwardRefPlaceholders.count(value); 335 } 336 337 /// This struct represents an isolated SSA name scope. This scope may contain 338 /// other nested non-isolated scopes. These scopes are used for operations 339 /// that are known to be isolated to allow for reusing names within their 340 /// regions, even if those names are used above. 341 struct IsolatedSSANameScope { 342 /// Record that a definition was added at the current scope. 343 void recordDefinition(StringRef def) { 344 definitionsPerScope.back().insert(def); 345 } 346 347 /// Push a nested name scope. 348 void pushSSANameScope() { definitionsPerScope.push_back({}); } 349 350 /// Pop a nested name scope. 351 void popSSANameScope() { 352 for (auto &def : definitionsPerScope.pop_back_val()) 353 values.erase(def.getKey()); 354 } 355 356 /// This keeps track of all of the SSA values we are tracking for each name 357 /// scope, indexed by their name. This has one entry per result number. 358 llvm::StringMap<SmallVector<ValueDefinition, 1>> values; 359 360 /// This keeps track of all of the values defined by a specific name scope. 361 SmallVector<llvm::StringSet<>, 2> definitionsPerScope; 362 }; 363 364 /// A list of isolated name scopes. 365 SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes; 366 367 /// This keeps track of the block names as well as the location of the first 368 /// reference for each nested name scope. This is used to diagnose invalid 369 /// block references and memorize them. 370 SmallVector<DenseMap<StringRef, BlockDefinition>, 2> blocksByName; 371 SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef; 372 373 /// These are all of the placeholders we've made along with the location of 374 /// their first reference, to allow checking for use of undefined values. 375 DenseMap<Value, SMLoc> forwardRefPlaceholders; 376 377 /// A set of operations whose locations reference aliases that have yet to 378 /// be resolved. 379 SmallVector<std::pair<Operation *, Token>, 8> opsWithDeferredLocs; 380 381 /// The builder used when creating parsed operation instances. 382 OpBuilder opBuilder; 383 384 /// The top level operation that holds all of the parsed operations. 385 Operation *topLevelOp; 386 }; 387 } // end anonymous namespace 388 389 OperationParser::~OperationParser() { 390 for (auto &fwd : forwardRefPlaceholders) { 391 // Drop all uses of undefined forward declared reference and destroy 392 // defining operation. 393 fwd.first.dropAllUses(); 394 fwd.first.getDefiningOp()->destroy(); 395 } 396 for (const auto &scope : forwardRef) { 397 for (const auto &fwd : scope) { 398 // Delete all blocks that were created as forward references but never 399 // included into a region. 400 fwd.first->dropAllUses(); 401 delete fwd.first; 402 } 403 } 404 } 405 406 /// After parsing is finished, this function must be called to see if there are 407 /// any remaining issues. 408 ParseResult OperationParser::finalize() { 409 // Check for any forward references that are left. If we find any, error 410 // out. 411 if (!forwardRefPlaceholders.empty()) { 412 SmallVector<const char *, 4> errors; 413 // Iteration over the map isn't deterministic, so sort by source location. 414 for (auto entry : forwardRefPlaceholders) 415 errors.push_back(entry.second.getPointer()); 416 llvm::array_pod_sort(errors.begin(), errors.end()); 417 418 for (auto entry : errors) { 419 auto loc = SMLoc::getFromPointer(entry); 420 emitError(loc, "use of undeclared SSA value name"); 421 } 422 return failure(); 423 } 424 425 // Resolve the locations of any deferred operations. 426 auto &attributeAliases = state.symbols.attributeAliasDefinitions; 427 for (std::pair<Operation *, Token> &it : opsWithDeferredLocs) { 428 llvm::SMLoc tokLoc = it.second.getLoc(); 429 StringRef identifier = it.second.getSpelling().drop_front(); 430 Attribute attr = attributeAliases.lookup(identifier); 431 if (!attr) 432 return emitError(tokLoc) << "operation location alias was never defined"; 433 434 LocationAttr locAttr = attr.dyn_cast<LocationAttr>(); 435 if (!locAttr) 436 return emitError(tokLoc) 437 << "expected location, but found '" << attr << "'"; 438 it.first->setLoc(locAttr); 439 } 440 441 // Pop the top level name scope. 442 return popSSANameScope(); 443 } 444 445 //===----------------------------------------------------------------------===// 446 // SSA Value Handling 447 //===----------------------------------------------------------------------===// 448 449 void OperationParser::pushSSANameScope(bool isIsolated) { 450 blocksByName.push_back(DenseMap<StringRef, BlockDefinition>()); 451 forwardRef.push_back(DenseMap<Block *, SMLoc>()); 452 453 // Push back a new name definition scope. 454 if (isIsolated) 455 isolatedNameScopes.push_back({}); 456 isolatedNameScopes.back().pushSSANameScope(); 457 } 458 459 ParseResult OperationParser::popSSANameScope() { 460 auto forwardRefInCurrentScope = forwardRef.pop_back_val(); 461 462 // Verify that all referenced blocks were defined. 463 if (!forwardRefInCurrentScope.empty()) { 464 SmallVector<std::pair<const char *, Block *>, 4> errors; 465 // Iteration over the map isn't deterministic, so sort by source location. 466 for (auto entry : forwardRefInCurrentScope) { 467 errors.push_back({entry.second.getPointer(), entry.first}); 468 // Add this block to the top-level region to allow for automatic cleanup. 469 topLevelOp->getRegion(0).push_back(entry.first); 470 } 471 llvm::array_pod_sort(errors.begin(), errors.end()); 472 473 for (auto entry : errors) { 474 auto loc = SMLoc::getFromPointer(entry.first); 475 emitError(loc, "reference to an undefined block"); 476 } 477 return failure(); 478 } 479 480 // Pop the next nested namescope. If there is only one internal namescope, 481 // just pop the isolated scope. 482 auto ¤tNameScope = isolatedNameScopes.back(); 483 if (currentNameScope.definitionsPerScope.size() == 1) 484 isolatedNameScopes.pop_back(); 485 else 486 currentNameScope.popSSANameScope(); 487 488 blocksByName.pop_back(); 489 return success(); 490 } 491 492 /// Register a definition of a value with the symbol table. 493 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) { 494 auto &entries = getSSAValueEntry(useInfo.name); 495 496 // Make sure there is a slot for this value. 497 if (entries.size() <= useInfo.number) 498 entries.resize(useInfo.number + 1); 499 500 // If we already have an entry for this, check to see if it was a definition 501 // or a forward reference. 502 if (auto existing = entries[useInfo.number].value) { 503 if (!isForwardRefPlaceholder(existing)) { 504 return emitError(useInfo.loc) 505 .append("redefinition of SSA value '", useInfo.name, "'") 506 .attachNote(getEncodedSourceLocation(entries[useInfo.number].loc)) 507 .append("previously defined here"); 508 } 509 510 if (existing.getType() != value.getType()) { 511 return emitError(useInfo.loc) 512 .append("definition of SSA value '", useInfo.name, "#", 513 useInfo.number, "' has type ", value.getType()) 514 .attachNote(getEncodedSourceLocation(entries[useInfo.number].loc)) 515 .append("previously used here with type ", existing.getType()); 516 } 517 518 // If it was a forward reference, update everything that used it to use 519 // the actual definition instead, delete the forward ref, and remove it 520 // from our set of forward references we track. 521 existing.replaceAllUsesWith(value); 522 existing.getDefiningOp()->destroy(); 523 forwardRefPlaceholders.erase(existing); 524 525 // If a definition of the value already exists, replace it in the assembly 526 // state. 527 if (state.asmState) 528 state.asmState->refineDefinition(existing, value); 529 } 530 531 /// Record this definition for the current scope. 532 entries[useInfo.number] = {value, useInfo.loc}; 533 recordDefinition(useInfo.name); 534 return success(); 535 } 536 537 /// Parse a (possibly empty) list of SSA operands. 538 /// 539 /// ssa-use-list ::= ssa-use (`,` ssa-use)* 540 /// ssa-use-list-opt ::= ssa-use-list? 541 /// 542 ParseResult 543 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) { 544 if (getToken().isNot(Token::percent_identifier)) 545 return success(); 546 return parseCommaSeparatedList([&]() -> ParseResult { 547 SSAUseInfo result; 548 if (parseSSAUse(result)) 549 return failure(); 550 results.push_back(result); 551 return success(); 552 }); 553 } 554 555 /// Parse a SSA operand for an operation. 556 /// 557 /// ssa-use ::= ssa-id 558 /// 559 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) { 560 result.name = getTokenSpelling(); 561 result.number = 0; 562 result.loc = getToken().getLoc(); 563 if (parseToken(Token::percent_identifier, "expected SSA operand")) 564 return failure(); 565 566 // If we have an attribute ID, it is a result number. 567 if (getToken().is(Token::hash_identifier)) { 568 if (auto value = getToken().getHashIdentifierNumber()) 569 result.number = value.getValue(); 570 else 571 return emitError("invalid SSA value result number"); 572 consumeToken(Token::hash_identifier); 573 } 574 575 return success(); 576 } 577 578 /// Given an unbound reference to an SSA value and its type, return the value 579 /// it specifies. This returns null on failure. 580 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) { 581 auto &entries = getSSAValueEntry(useInfo.name); 582 583 // Functor used to record the use of the given value if the assembly state 584 // field is populated. 585 auto maybeRecordUse = [&](Value value) { 586 if (state.asmState) 587 state.asmState->addUses(value, useInfo.loc); 588 return value; 589 }; 590 591 // If we have already seen a value of this name, return it. 592 if (useInfo.number < entries.size() && entries[useInfo.number].value) { 593 Value result = entries[useInfo.number].value; 594 // Check that the type matches the other uses. 595 if (result.getType() == type) 596 return maybeRecordUse(result); 597 598 emitError(useInfo.loc, "use of value '") 599 .append(useInfo.name, 600 "' expects different type than prior uses: ", type, " vs ", 601 result.getType()) 602 .attachNote(getEncodedSourceLocation(entries[useInfo.number].loc)) 603 .append("prior use here"); 604 return nullptr; 605 } 606 607 // Make sure we have enough slots for this. 608 if (entries.size() <= useInfo.number) 609 entries.resize(useInfo.number + 1); 610 611 // If the value has already been defined and this is an overly large result 612 // number, diagnose that. 613 if (entries[0].value && !isForwardRefPlaceholder(entries[0].value)) 614 return (emitError(useInfo.loc, "reference to invalid result number"), 615 nullptr); 616 617 // Otherwise, this is a forward reference. Create a placeholder and remember 618 // that we did so. 619 auto result = createForwardRefPlaceholder(useInfo.loc, type); 620 entries[useInfo.number] = {result, useInfo.loc}; 621 return maybeRecordUse(result); 622 } 623 624 /// Parse an SSA use with an associated type. 625 /// 626 /// ssa-use-and-type ::= ssa-use `:` type 627 ParseResult OperationParser::parseSSADefOrUseAndType( 628 function_ref<ParseResult(SSAUseInfo, Type)> action) { 629 SSAUseInfo useInfo; 630 if (parseSSAUse(useInfo) || 631 parseToken(Token::colon, "expected ':' and type for SSA operand")) 632 return failure(); 633 634 auto type = parseType(); 635 if (!type) 636 return failure(); 637 638 return action(useInfo, type); 639 } 640 641 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then 642 /// followed by a type list. 643 /// 644 /// ssa-use-and-type-list 645 /// ::= ssa-use-list ':' type-list-no-parens 646 /// 647 ParseResult OperationParser::parseOptionalSSAUseAndTypeList( 648 SmallVectorImpl<Value> &results) { 649 SmallVector<SSAUseInfo, 4> valueIDs; 650 if (parseOptionalSSAUseList(valueIDs)) 651 return failure(); 652 653 // If there were no operands, then there is no colon or type lists. 654 if (valueIDs.empty()) 655 return success(); 656 657 SmallVector<Type, 4> types; 658 if (parseToken(Token::colon, "expected ':' in operand list") || 659 parseTypeListNoParens(types)) 660 return failure(); 661 662 if (valueIDs.size() != types.size()) 663 return emitError("expected ") 664 << valueIDs.size() << " types to match operand list"; 665 666 results.reserve(valueIDs.size()); 667 for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) { 668 if (auto value = resolveSSAUse(valueIDs[i], types[i])) 669 results.push_back(value); 670 else 671 return failure(); 672 } 673 674 return success(); 675 } 676 677 /// Record that a definition was added at the current scope. 678 void OperationParser::recordDefinition(StringRef def) { 679 isolatedNameScopes.back().recordDefinition(def); 680 } 681 682 /// Get the value entry for the given SSA name. 683 auto OperationParser::getSSAValueEntry(StringRef name) 684 -> SmallVectorImpl<ValueDefinition> & { 685 return isolatedNameScopes.back().values[name]; 686 } 687 688 /// Create and remember a new placeholder for a forward reference. 689 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) { 690 // Forward references are always created as operations, because we just need 691 // something with a def/use chain. 692 // 693 // We create these placeholders as having an empty name, which we know 694 // cannot be created through normal user input, allowing us to distinguish 695 // them. 696 auto name = OperationName("placeholder", getContext()); 697 auto *op = Operation::create( 698 getEncodedSourceLocation(loc), name, type, /*operands=*/{}, 699 /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0); 700 forwardRefPlaceholders[op->getResult(0)] = loc; 701 return op->getResult(0); 702 } 703 704 //===----------------------------------------------------------------------===// 705 // Operation Parsing 706 //===----------------------------------------------------------------------===// 707 708 /// Parse an operation. 709 /// 710 /// operation ::= op-result-list? 711 /// (generic-operation | custom-operation) 712 /// trailing-location? 713 /// generic-operation ::= string-literal `(` ssa-use-list? `)` 714 /// successor-list? (`(` region-list `)`)? 715 /// attribute-dict? `:` function-type 716 /// custom-operation ::= bare-id custom-operation-format 717 /// op-result-list ::= op-result (`,` op-result)* `=` 718 /// op-result ::= ssa-id (`:` integer-literal) 719 /// 720 ParseResult OperationParser::parseOperation() { 721 auto loc = getToken().getLoc(); 722 SmallVector<ResultRecord, 1> resultIDs; 723 size_t numExpectedResults = 0; 724 if (getToken().is(Token::percent_identifier)) { 725 // Parse the group of result ids. 726 auto parseNextResult = [&]() -> ParseResult { 727 // Parse the next result id. 728 if (!getToken().is(Token::percent_identifier)) 729 return emitError("expected valid ssa identifier"); 730 731 Token nameTok = getToken(); 732 consumeToken(Token::percent_identifier); 733 734 // If the next token is a ':', we parse the expected result count. 735 size_t expectedSubResults = 1; 736 if (consumeIf(Token::colon)) { 737 // Check that the next token is an integer. 738 if (!getToken().is(Token::integer)) 739 return emitError("expected integer number of results"); 740 741 // Check that number of results is > 0. 742 auto val = getToken().getUInt64IntegerValue(); 743 if (!val.hasValue() || val.getValue() < 1) 744 return emitError("expected named operation to have atleast 1 result"); 745 consumeToken(Token::integer); 746 expectedSubResults = *val; 747 } 748 749 resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults, 750 nameTok.getLoc()); 751 numExpectedResults += expectedSubResults; 752 return success(); 753 }; 754 if (parseCommaSeparatedList(parseNextResult)) 755 return failure(); 756 757 if (parseToken(Token::equal, "expected '=' after SSA name")) 758 return failure(); 759 } 760 761 Operation *op; 762 Token nameTok = getToken(); 763 if (nameTok.is(Token::bare_identifier) || nameTok.isKeyword()) 764 op = parseCustomOperation(resultIDs); 765 else if (nameTok.is(Token::string)) 766 op = parseGenericOperation(); 767 else 768 return emitError("expected operation name in quotes"); 769 770 // If parsing of the basic operation failed, then this whole thing fails. 771 if (!op) 772 return failure(); 773 774 // If the operation had a name, register it. 775 if (!resultIDs.empty()) { 776 if (op->getNumResults() == 0) 777 return emitError(loc, "cannot name an operation with no results"); 778 if (numExpectedResults != op->getNumResults()) 779 return emitError(loc, "operation defines ") 780 << op->getNumResults() << " results but was provided " 781 << numExpectedResults << " to bind"; 782 783 // Add this operation to the assembly state if it was provided to populate. 784 if (state.asmState) { 785 unsigned resultIt = 0; 786 SmallVector<std::pair<unsigned, llvm::SMLoc>> asmResultGroups; 787 asmResultGroups.reserve(resultIDs.size()); 788 for (ResultRecord &record : resultIDs) { 789 asmResultGroups.emplace_back(resultIt, std::get<2>(record)); 790 resultIt += std::get<1>(record); 791 } 792 state.asmState->addDefinition(op, nameTok.getLocRange(), asmResultGroups); 793 } 794 795 // Add definitions for each of the result groups. 796 unsigned opResI = 0; 797 for (ResultRecord &resIt : resultIDs) { 798 for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) { 799 if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)}, 800 op->getResult(opResI++))) 801 return failure(); 802 } 803 } 804 805 // Add this operation to the assembly state if it was provided to populate. 806 } else if (state.asmState) { 807 state.asmState->addDefinition(op, nameTok.getLocRange()); 808 } 809 810 return success(); 811 } 812 813 /// Parse a single operation successor. 814 /// 815 /// successor ::= block-id 816 /// 817 ParseResult OperationParser::parseSuccessor(Block *&dest) { 818 // Verify branch is identifier and get the matching block. 819 if (!getToken().is(Token::caret_identifier)) 820 return emitError("expected block name"); 821 dest = getBlockNamed(getTokenSpelling(), getToken().getLoc()); 822 consumeToken(); 823 return success(); 824 } 825 826 /// Parse a comma-separated list of operation successors in brackets. 827 /// 828 /// successor-list ::= `[` successor (`,` successor )* `]` 829 /// 830 ParseResult 831 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) { 832 if (parseToken(Token::l_square, "expected '['")) 833 return failure(); 834 835 auto parseElt = [this, &destinations] { 836 Block *dest; 837 ParseResult res = parseSuccessor(dest); 838 destinations.push_back(dest); 839 return res; 840 }; 841 return parseCommaSeparatedListUntil(Token::r_square, parseElt, 842 /*allowEmptyList=*/false); 843 } 844 845 namespace { 846 // RAII-style guard for cleaning up the regions in the operation state before 847 // deleting them. Within the parser, regions may get deleted if parsing failed, 848 // and other errors may be present, in particular undominated uses. This makes 849 // sure such uses are deleted. 850 struct CleanupOpStateRegions { 851 ~CleanupOpStateRegions() { 852 SmallVector<Region *, 4> regionsToClean; 853 regionsToClean.reserve(state.regions.size()); 854 for (auto ®ion : state.regions) 855 if (region) 856 for (auto &block : *region) 857 block.dropAllDefinedValueUses(); 858 } 859 OperationState &state; 860 }; 861 } // namespace 862 863 Operation *OperationParser::parseGenericOperation() { 864 // Get location information for the operation. 865 auto srcLocation = getEncodedSourceLocation(getToken().getLoc()); 866 867 std::string name = getToken().getStringValue(); 868 if (name.empty()) 869 return (emitError("empty operation name is invalid"), nullptr); 870 if (name.find('\0') != StringRef::npos) 871 return (emitError("null character not allowed in operation name"), nullptr); 872 873 consumeToken(Token::string); 874 875 OperationState result(srcLocation, name); 876 877 // Lazy load dialects in the context as needed. 878 if (!result.name.getAbstractOperation()) { 879 StringRef dialectName = StringRef(name).split('.').first; 880 if (!getContext()->getLoadedDialect(dialectName) && 881 getContext()->getOrLoadDialect(dialectName)) { 882 result.name = OperationName(name, getContext()); 883 } 884 } 885 886 // Parse the operand list. 887 SmallVector<SSAUseInfo, 8> operandInfos; 888 if (parseToken(Token::l_paren, "expected '(' to start operand list") || 889 parseOptionalSSAUseList(operandInfos) || 890 parseToken(Token::r_paren, "expected ')' to end operand list")) { 891 return nullptr; 892 } 893 894 // Parse the successor list. 895 if (getToken().is(Token::l_square)) { 896 // Check if the operation is a known terminator. 897 const AbstractOperation *abstractOp = result.name.getAbstractOperation(); 898 if (abstractOp && !abstractOp->hasTrait<OpTrait::IsTerminator>()) 899 return emitError("successors in non-terminator"), nullptr; 900 901 SmallVector<Block *, 2> successors; 902 if (parseSuccessors(successors)) 903 return nullptr; 904 result.addSuccessors(successors); 905 } 906 907 // Parse the region list. 908 CleanupOpStateRegions guard{result}; 909 if (consumeIf(Token::l_paren)) { 910 do { 911 // Create temporary regions with the top level region as parent. 912 result.regions.emplace_back(new Region(topLevelOp)); 913 if (parseRegion(*result.regions.back(), /*entryArguments=*/{})) 914 return nullptr; 915 } while (consumeIf(Token::comma)); 916 if (parseToken(Token::r_paren, "expected ')' to end region list")) 917 return nullptr; 918 } 919 920 if (getToken().is(Token::l_brace)) { 921 if (parseAttributeDict(result.attributes)) 922 return nullptr; 923 } 924 925 if (parseToken(Token::colon, "expected ':' followed by operation type")) 926 return nullptr; 927 928 auto typeLoc = getToken().getLoc(); 929 auto type = parseType(); 930 if (!type) 931 return nullptr; 932 auto fnType = type.dyn_cast<FunctionType>(); 933 if (!fnType) 934 return (emitError(typeLoc, "expected function type"), nullptr); 935 936 result.addTypes(fnType.getResults()); 937 938 // Check that we have the right number of types for the operands. 939 auto operandTypes = fnType.getInputs(); 940 if (operandTypes.size() != operandInfos.size()) { 941 auto plural = "s"[operandInfos.size() == 1]; 942 return (emitError(typeLoc, "expected ") 943 << operandInfos.size() << " operand type" << plural 944 << " but had " << operandTypes.size(), 945 nullptr); 946 } 947 948 // Resolve all of the operands. 949 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) { 950 result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i])); 951 if (!result.operands.back()) 952 return nullptr; 953 } 954 955 // Create the operation and try to parse a location for it. 956 Operation *op = opBuilder.createOperation(result); 957 if (parseTrailingOperationLocation(op)) 958 return nullptr; 959 return op; 960 } 961 962 Operation *OperationParser::parseGenericOperation(Block *insertBlock, 963 Block::iterator insertPt) { 964 OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder); 965 opBuilder.setInsertionPoint(insertBlock, insertPt); 966 return parseGenericOperation(); 967 } 968 969 namespace { 970 class CustomOpAsmParser : public OpAsmParser { 971 public: 972 CustomOpAsmParser( 973 SMLoc nameLoc, ArrayRef<OperationParser::ResultRecord> resultIDs, 974 function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly, 975 bool isIsolatedFromAbove, StringRef opName, OperationParser &parser) 976 : nameLoc(nameLoc), resultIDs(resultIDs), parseAssembly(parseAssembly), 977 isIsolatedFromAbove(isIsolatedFromAbove), opName(opName), 978 parser(parser) { 979 (void)isIsolatedFromAbove; // Only used in assert, silence unused warning. 980 } 981 982 /// Parse an instance of the operation described by 'opDefinition' into the 983 /// provided operation state. 984 ParseResult parseOperation(OperationState &opState) { 985 if (parseAssembly(*this, opState)) 986 return failure(); 987 // Verify that the parsed attributes does not have duplicate attributes. 988 // This can happen if an attribute set during parsing is also specified in 989 // the attribute dictionary in the assembly, or the attribute is set 990 // multiple during parsing. 991 Optional<NamedAttribute> duplicate = opState.attributes.findDuplicate(); 992 if (duplicate) 993 return emitError(getNameLoc(), "attribute '") 994 << duplicate->first 995 << "' occurs more than once in the attribute list"; 996 return success(); 997 } 998 999 Operation *parseGenericOperation(Block *insertBlock, 1000 Block::iterator insertPt) final { 1001 return parser.parseGenericOperation(insertBlock, insertPt); 1002 } 1003 1004 //===--------------------------------------------------------------------===// 1005 // Utilities 1006 //===--------------------------------------------------------------------===// 1007 1008 /// Return if any errors were emitted during parsing. 1009 bool didEmitError() const { return emittedError; } 1010 1011 /// Emit a diagnostic at the specified location and return failure. 1012 InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override { 1013 emittedError = true; 1014 return parser.emitError(loc, "custom op '" + opName + "' " + message); 1015 } 1016 1017 llvm::SMLoc getCurrentLocation() override { 1018 return parser.getToken().getLoc(); 1019 } 1020 1021 Builder &getBuilder() const override { return parser.builder; } 1022 1023 /// Return the name of the specified result in the specified syntax, as well 1024 /// as the subelement in the name. For example, in this operation: 1025 /// 1026 /// %x, %y:2, %z = foo.op 1027 /// 1028 /// getResultName(0) == {"x", 0 } 1029 /// getResultName(1) == {"y", 0 } 1030 /// getResultName(2) == {"y", 1 } 1031 /// getResultName(3) == {"z", 0 } 1032 std::pair<StringRef, unsigned> 1033 getResultName(unsigned resultNo) const override { 1034 // Scan for the resultID that contains this result number. 1035 for (unsigned nameID = 0, e = resultIDs.size(); nameID != e; ++nameID) { 1036 const auto &entry = resultIDs[nameID]; 1037 if (resultNo < std::get<1>(entry)) { 1038 // Don't pass on the leading %. 1039 StringRef name = std::get<0>(entry).drop_front(); 1040 return {name, resultNo}; 1041 } 1042 resultNo -= std::get<1>(entry); 1043 } 1044 1045 // Invalid result number. 1046 return {"", ~0U}; 1047 } 1048 1049 /// Return the number of declared SSA results. This returns 4 for the foo.op 1050 /// example in the comment for getResultName. 1051 size_t getNumResults() const override { 1052 size_t count = 0; 1053 for (auto &entry : resultIDs) 1054 count += std::get<1>(entry); 1055 return count; 1056 } 1057 1058 llvm::SMLoc getNameLoc() const override { return nameLoc; } 1059 1060 //===--------------------------------------------------------------------===// 1061 // Token Parsing 1062 //===--------------------------------------------------------------------===// 1063 1064 /// Parse a `->` token. 1065 ParseResult parseArrow() override { 1066 return parser.parseToken(Token::arrow, "expected '->'"); 1067 } 1068 1069 /// Parses a `->` if present. 1070 ParseResult parseOptionalArrow() override { 1071 return success(parser.consumeIf(Token::arrow)); 1072 } 1073 1074 /// Parse a '{' token. 1075 ParseResult parseLBrace() override { 1076 return parser.parseToken(Token::l_brace, "expected '{'"); 1077 } 1078 1079 /// Parse a '{' token if present 1080 ParseResult parseOptionalLBrace() override { 1081 return success(parser.consumeIf(Token::l_brace)); 1082 } 1083 1084 /// Parse a `}` token. 1085 ParseResult parseRBrace() override { 1086 return parser.parseToken(Token::r_brace, "expected '}'"); 1087 } 1088 1089 /// Parse a `}` token if present 1090 ParseResult parseOptionalRBrace() override { 1091 return success(parser.consumeIf(Token::r_brace)); 1092 } 1093 1094 /// Parse a `:` token. 1095 ParseResult parseColon() override { 1096 return parser.parseToken(Token::colon, "expected ':'"); 1097 } 1098 1099 /// Parse a `:` token if present. 1100 ParseResult parseOptionalColon() override { 1101 return success(parser.consumeIf(Token::colon)); 1102 } 1103 1104 /// Parse a `,` token. 1105 ParseResult parseComma() override { 1106 return parser.parseToken(Token::comma, "expected ','"); 1107 } 1108 1109 /// Parse a `,` token if present. 1110 ParseResult parseOptionalComma() override { 1111 return success(parser.consumeIf(Token::comma)); 1112 } 1113 1114 /// Parses a `...` if present. 1115 ParseResult parseOptionalEllipsis() override { 1116 return success(parser.consumeIf(Token::ellipsis)); 1117 } 1118 1119 /// Parse a `=` token. 1120 ParseResult parseEqual() override { 1121 return parser.parseToken(Token::equal, "expected '='"); 1122 } 1123 1124 /// Parse a `=` token if present. 1125 ParseResult parseOptionalEqual() override { 1126 return success(parser.consumeIf(Token::equal)); 1127 } 1128 1129 /// Parse a '<' token. 1130 ParseResult parseLess() override { 1131 return parser.parseToken(Token::less, "expected '<'"); 1132 } 1133 1134 /// Parse a '<' token if present. 1135 ParseResult parseOptionalLess() override { 1136 return success(parser.consumeIf(Token::less)); 1137 } 1138 1139 /// Parse a '>' token. 1140 ParseResult parseGreater() override { 1141 return parser.parseToken(Token::greater, "expected '>'"); 1142 } 1143 1144 /// Parse a '>' token if present. 1145 ParseResult parseOptionalGreater() override { 1146 return success(parser.consumeIf(Token::greater)); 1147 } 1148 1149 /// Parse a `(` token. 1150 ParseResult parseLParen() override { 1151 return parser.parseToken(Token::l_paren, "expected '('"); 1152 } 1153 1154 /// Parses a '(' if present. 1155 ParseResult parseOptionalLParen() override { 1156 return success(parser.consumeIf(Token::l_paren)); 1157 } 1158 1159 /// Parse a `)` token. 1160 ParseResult parseRParen() override { 1161 return parser.parseToken(Token::r_paren, "expected ')'"); 1162 } 1163 1164 /// Parses a ')' if present. 1165 ParseResult parseOptionalRParen() override { 1166 return success(parser.consumeIf(Token::r_paren)); 1167 } 1168 1169 /// Parse a `[` token. 1170 ParseResult parseLSquare() override { 1171 return parser.parseToken(Token::l_square, "expected '['"); 1172 } 1173 1174 /// Parses a '[' if present. 1175 ParseResult parseOptionalLSquare() override { 1176 return success(parser.consumeIf(Token::l_square)); 1177 } 1178 1179 /// Parse a `]` token. 1180 ParseResult parseRSquare() override { 1181 return parser.parseToken(Token::r_square, "expected ']'"); 1182 } 1183 1184 /// Parses a ']' if present. 1185 ParseResult parseOptionalRSquare() override { 1186 return success(parser.consumeIf(Token::r_square)); 1187 } 1188 1189 /// Parses a '?' token. 1190 ParseResult parseQuestion() override { 1191 return parser.parseToken(Token::question, "expected '?'"); 1192 } 1193 1194 /// Parses a '?' token if present. 1195 ParseResult parseOptionalQuestion() override { 1196 return success(parser.consumeIf(Token::question)); 1197 } 1198 1199 /// Parses a '+' token. 1200 ParseResult parsePlus() override { 1201 return parser.parseToken(Token::plus, "expected '+'"); 1202 } 1203 1204 /// Parses a '+' token if present. 1205 ParseResult parseOptionalPlus() override { 1206 return success(parser.consumeIf(Token::plus)); 1207 } 1208 1209 /// Parses a '*' token. 1210 ParseResult parseStar() override { 1211 return parser.parseToken(Token::star, "expected '*'"); 1212 } 1213 1214 /// Parses a '*' token if present. 1215 ParseResult parseOptionalStar() override { 1216 return success(parser.consumeIf(Token::star)); 1217 } 1218 1219 /// Parse an optional integer value from the stream. 1220 OptionalParseResult parseOptionalInteger(uint64_t &result) override { 1221 return parser.parseOptionalInteger(result); 1222 } 1223 1224 //===--------------------------------------------------------------------===// 1225 // Attribute Parsing 1226 //===--------------------------------------------------------------------===// 1227 1228 /// Parse an arbitrary attribute of a given type and return it in result. 1229 ParseResult parseAttribute(Attribute &result, Type type) override { 1230 result = parser.parseAttribute(type); 1231 return success(static_cast<bool>(result)); 1232 } 1233 1234 /// Parse an optional attribute. 1235 template <typename AttrT> 1236 OptionalParseResult 1237 parseOptionalAttributeAndAddToList(AttrT &result, Type type, 1238 StringRef attrName, NamedAttrList &attrs) { 1239 OptionalParseResult parseResult = 1240 parser.parseOptionalAttribute(result, type); 1241 if (parseResult.hasValue() && succeeded(*parseResult)) 1242 attrs.push_back(parser.builder.getNamedAttr(attrName, result)); 1243 return parseResult; 1244 } 1245 OptionalParseResult parseOptionalAttribute(Attribute &result, Type type, 1246 StringRef attrName, 1247 NamedAttrList &attrs) override { 1248 return parseOptionalAttributeAndAddToList(result, type, attrName, attrs); 1249 } 1250 OptionalParseResult parseOptionalAttribute(ArrayAttr &result, Type type, 1251 StringRef attrName, 1252 NamedAttrList &attrs) override { 1253 return parseOptionalAttributeAndAddToList(result, type, attrName, attrs); 1254 } 1255 OptionalParseResult parseOptionalAttribute(StringAttr &result, Type type, 1256 StringRef attrName, 1257 NamedAttrList &attrs) override { 1258 return parseOptionalAttributeAndAddToList(result, type, attrName, attrs); 1259 } 1260 1261 /// Parse a named dictionary into 'result' if it is present. 1262 ParseResult parseOptionalAttrDict(NamedAttrList &result) override { 1263 if (parser.getToken().isNot(Token::l_brace)) 1264 return success(); 1265 return parser.parseAttributeDict(result); 1266 } 1267 1268 /// Parse a named dictionary into 'result' if the `attributes` keyword is 1269 /// present. 1270 ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result) override { 1271 if (failed(parseOptionalKeyword("attributes"))) 1272 return success(); 1273 return parser.parseAttributeDict(result); 1274 } 1275 1276 /// Parse an affine map instance into 'map'. 1277 ParseResult parseAffineMap(AffineMap &map) override { 1278 return parser.parseAffineMapReference(map); 1279 } 1280 1281 /// Parse an integer set instance into 'set'. 1282 ParseResult printIntegerSet(IntegerSet &set) override { 1283 return parser.parseIntegerSetReference(set); 1284 } 1285 1286 //===--------------------------------------------------------------------===// 1287 // Identifier Parsing 1288 //===--------------------------------------------------------------------===// 1289 1290 /// Returns true if the current token corresponds to a keyword. 1291 bool isCurrentTokenAKeyword() const { 1292 return parser.getToken().is(Token::bare_identifier) || 1293 parser.getToken().isKeyword(); 1294 } 1295 1296 /// Parse the given keyword if present. 1297 ParseResult parseOptionalKeyword(StringRef keyword) override { 1298 // Check that the current token has the same spelling. 1299 if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword) 1300 return failure(); 1301 parser.consumeToken(); 1302 return success(); 1303 } 1304 1305 /// Parse a keyword, if present, into 'keyword'. 1306 ParseResult parseOptionalKeyword(StringRef *keyword) override { 1307 // Check that the current token is a keyword. 1308 if (!isCurrentTokenAKeyword()) 1309 return failure(); 1310 1311 *keyword = parser.getTokenSpelling(); 1312 parser.consumeToken(); 1313 return success(); 1314 } 1315 1316 /// Parse a keyword if it is one of the 'allowedKeywords'. 1317 ParseResult 1318 parseOptionalKeyword(StringRef *keyword, 1319 ArrayRef<StringRef> allowedKeywords) override { 1320 // Check that the current token is a keyword. 1321 if (!isCurrentTokenAKeyword()) 1322 return failure(); 1323 1324 StringRef currentKeyword = parser.getTokenSpelling(); 1325 if (llvm::is_contained(allowedKeywords, currentKeyword)) { 1326 *keyword = currentKeyword; 1327 parser.consumeToken(); 1328 return success(); 1329 } 1330 1331 return failure(); 1332 } 1333 1334 /// Parse an optional @-identifier and store it (without the '@' symbol) in a 1335 /// string attribute named 'attrName'. 1336 ParseResult parseOptionalSymbolName(StringAttr &result, StringRef attrName, 1337 NamedAttrList &attrs) override { 1338 Token atToken = parser.getToken(); 1339 if (atToken.isNot(Token::at_identifier)) 1340 return failure(); 1341 1342 result = getBuilder().getStringAttr(atToken.getSymbolReference()); 1343 attrs.push_back(getBuilder().getNamedAttr(attrName, result)); 1344 parser.consumeToken(); 1345 return success(); 1346 } 1347 1348 //===--------------------------------------------------------------------===// 1349 // Operand Parsing 1350 //===--------------------------------------------------------------------===// 1351 1352 /// Parse a single operand. 1353 ParseResult parseOperand(OperandType &result) override { 1354 OperationParser::SSAUseInfo useInfo; 1355 if (parser.parseSSAUse(useInfo)) 1356 return failure(); 1357 1358 result = {useInfo.loc, useInfo.name, useInfo.number}; 1359 return success(); 1360 } 1361 1362 /// Parse a single operand if present. 1363 OptionalParseResult parseOptionalOperand(OperandType &result) override { 1364 if (parser.getToken().is(Token::percent_identifier)) 1365 return parseOperand(result); 1366 return llvm::None; 1367 } 1368 1369 /// Parse zero or more SSA comma-separated operand references with a specified 1370 /// surrounding delimiter, and an optional required operand count. 1371 ParseResult parseOperandList(SmallVectorImpl<OperandType> &result, 1372 int requiredOperandCount = -1, 1373 Delimiter delimiter = Delimiter::None) override { 1374 return parseOperandOrRegionArgList(result, /*isOperandList=*/true, 1375 requiredOperandCount, delimiter); 1376 } 1377 1378 /// Parse zero or more SSA comma-separated operand or region arguments with 1379 /// optional surrounding delimiter and required operand count. 1380 ParseResult 1381 parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result, 1382 bool isOperandList, int requiredOperandCount = -1, 1383 Delimiter delimiter = Delimiter::None) { 1384 auto startLoc = parser.getToken().getLoc(); 1385 1386 // Handle delimiters. 1387 switch (delimiter) { 1388 case Delimiter::None: 1389 // Don't check for the absence of a delimiter if the number of operands 1390 // is unknown (and hence the operand list could be empty). 1391 if (requiredOperandCount == -1) 1392 break; 1393 // Token already matches an identifier and so can't be a delimiter. 1394 if (parser.getToken().is(Token::percent_identifier)) 1395 break; 1396 // Test against known delimiters. 1397 if (parser.getToken().is(Token::l_paren) || 1398 parser.getToken().is(Token::l_square)) 1399 return emitError(startLoc, "unexpected delimiter"); 1400 return emitError(startLoc, "invalid operand"); 1401 case Delimiter::OptionalParen: 1402 if (parser.getToken().isNot(Token::l_paren)) 1403 return success(); 1404 LLVM_FALLTHROUGH; 1405 case Delimiter::Paren: 1406 if (parser.parseToken(Token::l_paren, "expected '(' in operand list")) 1407 return failure(); 1408 break; 1409 case Delimiter::OptionalSquare: 1410 if (parser.getToken().isNot(Token::l_square)) 1411 return success(); 1412 LLVM_FALLTHROUGH; 1413 case Delimiter::Square: 1414 if (parser.parseToken(Token::l_square, "expected '[' in operand list")) 1415 return failure(); 1416 break; 1417 } 1418 1419 // Check for zero operands. 1420 if (parser.getToken().is(Token::percent_identifier)) { 1421 do { 1422 OperandType operandOrArg; 1423 if (isOperandList ? parseOperand(operandOrArg) 1424 : parseRegionArgument(operandOrArg)) 1425 return failure(); 1426 result.push_back(operandOrArg); 1427 } while (parser.consumeIf(Token::comma)); 1428 } 1429 1430 // Handle delimiters. If we reach here, the optional delimiters were 1431 // present, so we need to parse their closing one. 1432 switch (delimiter) { 1433 case Delimiter::None: 1434 break; 1435 case Delimiter::OptionalParen: 1436 case Delimiter::Paren: 1437 if (parser.parseToken(Token::r_paren, "expected ')' in operand list")) 1438 return failure(); 1439 break; 1440 case Delimiter::OptionalSquare: 1441 case Delimiter::Square: 1442 if (parser.parseToken(Token::r_square, "expected ']' in operand list")) 1443 return failure(); 1444 break; 1445 } 1446 1447 if (requiredOperandCount != -1 && 1448 result.size() != static_cast<size_t>(requiredOperandCount)) 1449 return emitError(startLoc, "expected ") 1450 << requiredOperandCount << " operands"; 1451 return success(); 1452 } 1453 1454 /// Parse zero or more trailing SSA comma-separated trailing operand 1455 /// references with a specified surrounding delimiter, and an optional 1456 /// required operand count. A leading comma is expected before the operands. 1457 ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result, 1458 int requiredOperandCount, 1459 Delimiter delimiter) override { 1460 if (parser.getToken().is(Token::comma)) { 1461 parseComma(); 1462 return parseOperandList(result, requiredOperandCount, delimiter); 1463 } 1464 if (requiredOperandCount != -1) 1465 return emitError(parser.getToken().getLoc(), "expected ") 1466 << requiredOperandCount << " operands"; 1467 return success(); 1468 } 1469 1470 /// Resolve an operand to an SSA value, emitting an error on failure. 1471 ParseResult resolveOperand(const OperandType &operand, Type type, 1472 SmallVectorImpl<Value> &result) override { 1473 OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number, 1474 operand.location}; 1475 if (auto value = parser.resolveSSAUse(operandInfo, type)) { 1476 result.push_back(value); 1477 return success(); 1478 } 1479 return failure(); 1480 } 1481 1482 /// Parse an AffineMap of SSA ids. 1483 ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands, 1484 Attribute &mapAttr, StringRef attrName, 1485 NamedAttrList &attrs, 1486 Delimiter delimiter) override { 1487 SmallVector<OperandType, 2> dimOperands; 1488 SmallVector<OperandType, 1> symOperands; 1489 1490 auto parseElement = [&](bool isSymbol) -> ParseResult { 1491 OperandType operand; 1492 if (parseOperand(operand)) 1493 return failure(); 1494 if (isSymbol) 1495 symOperands.push_back(operand); 1496 else 1497 dimOperands.push_back(operand); 1498 return success(); 1499 }; 1500 1501 AffineMap map; 1502 if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter)) 1503 return failure(); 1504 // Add AffineMap attribute. 1505 if (map) { 1506 mapAttr = AffineMapAttr::get(map); 1507 attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr)); 1508 } 1509 1510 // Add dim operands before symbol operands in 'operands'. 1511 operands.assign(dimOperands.begin(), dimOperands.end()); 1512 operands.append(symOperands.begin(), symOperands.end()); 1513 return success(); 1514 } 1515 1516 //===--------------------------------------------------------------------===// 1517 // Region Parsing 1518 //===--------------------------------------------------------------------===// 1519 1520 /// Parse a region that takes `arguments` of `argTypes` types. This 1521 /// effectively defines the SSA values of `arguments` and assigns their type. 1522 ParseResult parseRegion(Region ®ion, ArrayRef<OperandType> arguments, 1523 ArrayRef<Type> argTypes, 1524 bool enableNameShadowing) override { 1525 assert(arguments.size() == argTypes.size() && 1526 "mismatching number of arguments and types"); 1527 1528 SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2> 1529 regionArguments; 1530 for (auto pair : llvm::zip(arguments, argTypes)) { 1531 const OperandType &operand = std::get<0>(pair); 1532 Type type = std::get<1>(pair); 1533 OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number, 1534 operand.location}; 1535 regionArguments.emplace_back(operandInfo, type); 1536 } 1537 1538 // Try to parse the region. 1539 (void)isIsolatedFromAbove; 1540 assert((!enableNameShadowing || isIsolatedFromAbove) && 1541 "name shadowing is only allowed on isolated regions"); 1542 if (parser.parseRegion(region, regionArguments, enableNameShadowing)) 1543 return failure(); 1544 return success(); 1545 } 1546 1547 /// Parses a region if present. 1548 OptionalParseResult parseOptionalRegion(Region ®ion, 1549 ArrayRef<OperandType> arguments, 1550 ArrayRef<Type> argTypes, 1551 bool enableNameShadowing) override { 1552 if (parser.getToken().isNot(Token::l_brace)) 1553 return llvm::None; 1554 return parseRegion(region, arguments, argTypes, enableNameShadowing); 1555 } 1556 1557 /// Parses a region if present. If the region is present, a new region is 1558 /// allocated and placed in `region`. If no region is present, `region` 1559 /// remains untouched. 1560 OptionalParseResult 1561 parseOptionalRegion(std::unique_ptr<Region> ®ion, 1562 ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes, 1563 bool enableNameShadowing = false) override { 1564 if (parser.getToken().isNot(Token::l_brace)) 1565 return llvm::None; 1566 std::unique_ptr<Region> newRegion = std::make_unique<Region>(); 1567 if (parseRegion(*newRegion, arguments, argTypes, enableNameShadowing)) 1568 return failure(); 1569 1570 region = std::move(newRegion); 1571 return success(); 1572 } 1573 1574 /// Parse a region argument. The type of the argument will be resolved later 1575 /// by a call to `parseRegion`. 1576 ParseResult parseRegionArgument(OperandType &argument) override { 1577 return parseOperand(argument); 1578 } 1579 1580 /// Parse a region argument if present. 1581 ParseResult parseOptionalRegionArgument(OperandType &argument) override { 1582 if (parser.getToken().isNot(Token::percent_identifier)) 1583 return success(); 1584 return parseRegionArgument(argument); 1585 } 1586 1587 ParseResult 1588 parseRegionArgumentList(SmallVectorImpl<OperandType> &result, 1589 int requiredOperandCount = -1, 1590 Delimiter delimiter = Delimiter::None) override { 1591 return parseOperandOrRegionArgList(result, /*isOperandList=*/false, 1592 requiredOperandCount, delimiter); 1593 } 1594 1595 //===--------------------------------------------------------------------===// 1596 // Successor Parsing 1597 //===--------------------------------------------------------------------===// 1598 1599 /// Parse a single operation successor. 1600 ParseResult parseSuccessor(Block *&dest) override { 1601 return parser.parseSuccessor(dest); 1602 } 1603 1604 /// Parse an optional operation successor and its operand list. 1605 OptionalParseResult parseOptionalSuccessor(Block *&dest) override { 1606 if (parser.getToken().isNot(Token::caret_identifier)) 1607 return llvm::None; 1608 return parseSuccessor(dest); 1609 } 1610 1611 /// Parse a single operation successor and its operand list. 1612 ParseResult 1613 parseSuccessorAndUseList(Block *&dest, 1614 SmallVectorImpl<Value> &operands) override { 1615 if (parseSuccessor(dest)) 1616 return failure(); 1617 1618 // Handle optional arguments. 1619 if (succeeded(parseOptionalLParen()) && 1620 (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) { 1621 return failure(); 1622 } 1623 return success(); 1624 } 1625 1626 //===--------------------------------------------------------------------===// 1627 // Type Parsing 1628 //===--------------------------------------------------------------------===// 1629 1630 /// Parse a type. 1631 ParseResult parseType(Type &result) override { 1632 return failure(!(result = parser.parseType())); 1633 } 1634 1635 /// Parse an optional type. 1636 OptionalParseResult parseOptionalType(Type &result) override { 1637 return parser.parseOptionalType(result); 1638 } 1639 1640 /// Parse an arrow followed by a type list. 1641 ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override { 1642 if (parseArrow() || parser.parseFunctionResultTypes(result)) 1643 return failure(); 1644 return success(); 1645 } 1646 1647 /// Parse an optional arrow followed by a type list. 1648 ParseResult 1649 parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override { 1650 if (!parser.consumeIf(Token::arrow)) 1651 return success(); 1652 return parser.parseFunctionResultTypes(result); 1653 } 1654 1655 /// Parse a colon followed by a type. 1656 ParseResult parseColonType(Type &result) override { 1657 return failure(parser.parseToken(Token::colon, "expected ':'") || 1658 !(result = parser.parseType())); 1659 } 1660 1661 /// Parse a colon followed by a type list, which must have at least one type. 1662 ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override { 1663 if (parser.parseToken(Token::colon, "expected ':'")) 1664 return failure(); 1665 return parser.parseTypeListNoParens(result); 1666 } 1667 1668 /// Parse an optional colon followed by a type list, which if present must 1669 /// have at least one type. 1670 ParseResult 1671 parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override { 1672 if (!parser.consumeIf(Token::colon)) 1673 return success(); 1674 return parser.parseTypeListNoParens(result); 1675 } 1676 1677 /// Parse a list of assignments of the form 1678 /// (%x1 = %y1, %x2 = %y2, ...). 1679 OptionalParseResult 1680 parseOptionalAssignmentList(SmallVectorImpl<OperandType> &lhs, 1681 SmallVectorImpl<OperandType> &rhs) override { 1682 if (failed(parseOptionalLParen())) 1683 return llvm::None; 1684 1685 auto parseElt = [&]() -> ParseResult { 1686 OperandType regionArg, operand; 1687 if (parseRegionArgument(regionArg) || parseEqual() || 1688 parseOperand(operand)) 1689 return failure(); 1690 lhs.push_back(regionArg); 1691 rhs.push_back(operand); 1692 return success(); 1693 }; 1694 return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt); 1695 } 1696 1697 /// Parse a list of assignments of the form 1698 /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...). 1699 OptionalParseResult 1700 parseOptionalAssignmentListWithTypes(SmallVectorImpl<OperandType> &lhs, 1701 SmallVectorImpl<OperandType> &rhs, 1702 SmallVectorImpl<Type> &types) override { 1703 if (failed(parseOptionalLParen())) 1704 return llvm::None; 1705 1706 auto parseElt = [&]() -> ParseResult { 1707 OperandType regionArg, operand; 1708 Type type; 1709 if (parseRegionArgument(regionArg) || parseEqual() || 1710 parseOperand(operand) || parseColon() || parseType(type)) 1711 return failure(); 1712 lhs.push_back(regionArg); 1713 rhs.push_back(operand); 1714 types.push_back(type); 1715 return success(); 1716 }; 1717 return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt); 1718 } 1719 1720 private: 1721 /// The source location of the operation name. 1722 SMLoc nameLoc; 1723 1724 /// Information about the result name specifiers. 1725 ArrayRef<OperationParser::ResultRecord> resultIDs; 1726 1727 /// The abstract information of the operation. 1728 function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly; 1729 bool isIsolatedFromAbove; 1730 StringRef opName; 1731 1732 /// The main operation parser. 1733 OperationParser &parser; 1734 1735 /// A flag that indicates if any errors were emitted during parsing. 1736 bool emittedError = false; 1737 }; 1738 } // end anonymous namespace. 1739 1740 Operation * 1741 OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) { 1742 llvm::SMLoc opLoc = getToken().getLoc(); 1743 StringRef opName = getTokenSpelling(); 1744 auto *opDefinition = AbstractOperation::lookup(opName, getContext()); 1745 Dialect *dialect = nullptr; 1746 if (opDefinition) { 1747 dialect = &opDefinition->dialect; 1748 } else { 1749 if (opName.contains('.')) { 1750 // This op has a dialect, we try to check if we can register it in the 1751 // context on the fly. 1752 StringRef dialectName = opName.split('.').first; 1753 dialect = getContext()->getLoadedDialect(dialectName); 1754 if (!dialect && (dialect = getContext()->getOrLoadDialect(dialectName))) 1755 opDefinition = AbstractOperation::lookup(opName, getContext()); 1756 } else { 1757 // If the operation name has no namespace prefix we treat it as a standard 1758 // operation and prefix it with "std". 1759 // TODO: Would it be better to just build a mapping of the registered 1760 // operations in the standard dialect? 1761 if (getContext()->getOrLoadDialect("std")) { 1762 opDefinition = AbstractOperation::lookup(Twine("std." + opName).str(), 1763 getContext()); 1764 if (opDefinition) 1765 opName = opDefinition->name.strref(); 1766 } 1767 } 1768 } 1769 1770 // This is the actual hook for the custom op parsing, usually implemented by 1771 // the op itself (`Op::parse()`). We retrieve it either from the 1772 // AbstractOperation or from the Dialect. 1773 std::function<ParseResult(OpAsmParser &, OperationState &)> parseAssemblyFn; 1774 bool isIsolatedFromAbove = false; 1775 1776 if (opDefinition) { 1777 parseAssemblyFn = opDefinition->getParseAssemblyFn(); 1778 isIsolatedFromAbove = 1779 opDefinition->hasTrait<OpTrait::IsIsolatedFromAbove>(); 1780 } else { 1781 Optional<Dialect::ParseOpHook> dialectHook; 1782 if (dialect) 1783 dialectHook = dialect->getParseOperationHook(opName); 1784 if (!dialectHook.hasValue()) { 1785 emitError(opLoc) << "custom op '" << opName << "' is unknown"; 1786 return nullptr; 1787 } 1788 parseAssemblyFn = *dialectHook; 1789 } 1790 1791 consumeToken(); 1792 1793 // If the custom op parser crashes, produce some indication to help 1794 // debugging. 1795 std::string opNameStr = opName.str(); 1796 llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'", 1797 opNameStr.c_str()); 1798 1799 // Get location information for the operation. 1800 auto srcLocation = getEncodedSourceLocation(opLoc); 1801 1802 // Have the op implementation take a crack and parsing this. 1803 OperationState opState(srcLocation, opName); 1804 CleanupOpStateRegions guard{opState}; 1805 CustomOpAsmParser opAsmParser(opLoc, resultIDs, parseAssemblyFn, 1806 isIsolatedFromAbove, opName, *this); 1807 if (opAsmParser.parseOperation(opState)) 1808 return nullptr; 1809 1810 // If it emitted an error, we failed. 1811 if (opAsmParser.didEmitError()) 1812 return nullptr; 1813 1814 // Otherwise, create the operation and try to parse a location for it. 1815 Operation *op = opBuilder.createOperation(opState); 1816 if (parseTrailingOperationLocation(op)) 1817 return nullptr; 1818 return op; 1819 } 1820 1821 ParseResult OperationParser::parseTrailingOperationLocation(Operation *op) { 1822 // If there is a 'loc' we parse a trailing location. 1823 if (!consumeIf(Token::kw_loc)) 1824 return success(); 1825 if (parseToken(Token::l_paren, "expected '(' in location")) 1826 return failure(); 1827 Token tok = getToken(); 1828 1829 // Check to see if we are parsing a location alias. 1830 LocationAttr directLoc; 1831 if (tok.is(Token::hash_identifier)) { 1832 consumeToken(); 1833 1834 StringRef identifier = tok.getSpelling().drop_front(); 1835 if (identifier.contains('.')) { 1836 return emitError(tok.getLoc()) 1837 << "expected location, but found dialect attribute: '#" 1838 << identifier << "'"; 1839 } 1840 1841 // If this alias can be resolved, do it now. 1842 Attribute attr = state.symbols.attributeAliasDefinitions.lookup(identifier); 1843 if (attr) { 1844 if (!(directLoc = attr.dyn_cast<LocationAttr>())) 1845 return emitError(tok.getLoc()) 1846 << "expected location, but found '" << attr << "'"; 1847 } else { 1848 // Otherwise, remember this operation and resolve its location later. 1849 opsWithDeferredLocs.emplace_back(op, tok); 1850 } 1851 1852 // Otherwise, we parse the location directly. 1853 } else if (parseLocationInstance(directLoc)) { 1854 return failure(); 1855 } 1856 1857 if (parseToken(Token::r_paren, "expected ')' in location")) 1858 return failure(); 1859 1860 if (directLoc) 1861 op->setLoc(directLoc); 1862 return success(); 1863 } 1864 1865 //===----------------------------------------------------------------------===// 1866 // Region Parsing 1867 //===----------------------------------------------------------------------===// 1868 1869 /// Region. 1870 /// 1871 /// region ::= '{' region-body 1872 /// 1873 ParseResult OperationParser::parseRegion( 1874 Region ®ion, 1875 ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments, 1876 bool isIsolatedNameScope) { 1877 // Parse the '{'. 1878 Token lBraceTok = getToken(); 1879 if (parseToken(Token::l_brace, "expected '{' to begin a region")) 1880 return failure(); 1881 1882 // Check for an empty region. 1883 if (entryArguments.empty() && consumeIf(Token::r_brace)) 1884 return success(); 1885 auto currentPt = opBuilder.saveInsertionPoint(); 1886 1887 // Push a new named value scope. 1888 pushSSANameScope(isIsolatedNameScope); 1889 1890 // Parse the first block directly to allow for it to be unnamed. 1891 auto owning_block = std::make_unique<Block>(); 1892 Block *block = owning_block.get(); 1893 1894 // If this block is not defined in the source file, add a definition for it 1895 // now in the assembly state. Blocks with a name will be defined when the name 1896 // is parsed. 1897 if (state.asmState && getToken().isNot(Token::caret_identifier)) 1898 state.asmState->addDefinition(block, lBraceTok.getLoc()); 1899 1900 // Add arguments to the entry block. 1901 if (!entryArguments.empty()) { 1902 for (auto &placeholderArgPair : entryArguments) { 1903 auto &argInfo = placeholderArgPair.first; 1904 1905 // Ensure that the argument was not already defined. 1906 if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) { 1907 return emitError(argInfo.loc, "region entry argument '" + argInfo.name + 1908 "' is already in use") 1909 .attachNote(getEncodedSourceLocation(*defLoc)) 1910 << "previously referenced here"; 1911 } 1912 BlockArgument arg = block->addArgument(placeholderArgPair.second); 1913 1914 // Add a definition of this arg to the assembly state if provided. 1915 if (state.asmState) 1916 state.asmState->addDefinition(arg, argInfo.loc); 1917 1918 // Record the definition for this argument. 1919 if (addDefinition(argInfo, arg)) 1920 return failure(); 1921 } 1922 1923 // If we had named arguments, then don't allow a block name. 1924 if (getToken().is(Token::caret_identifier)) 1925 return emitError("invalid block name in region with named arguments"); 1926 } 1927 1928 if (parseBlock(block)) 1929 return failure(); 1930 1931 // Verify that no other arguments were parsed. 1932 if (!entryArguments.empty() && 1933 block->getNumArguments() > entryArguments.size()) { 1934 return emitError("entry block arguments were already defined"); 1935 } 1936 1937 // Parse the rest of the region. 1938 region.push_back(owning_block.release()); 1939 if (parseRegionBody(region)) 1940 return failure(); 1941 1942 // Pop the SSA value scope for this region. 1943 if (popSSANameScope()) 1944 return failure(); 1945 1946 // Reset the original insertion point. 1947 opBuilder.restoreInsertionPoint(currentPt); 1948 return success(); 1949 } 1950 1951 /// Region. 1952 /// 1953 /// region-body ::= block* '}' 1954 /// 1955 ParseResult OperationParser::parseRegionBody(Region ®ion) { 1956 // Parse the list of blocks. 1957 while (!consumeIf(Token::r_brace)) { 1958 Block *newBlock = nullptr; 1959 if (parseBlock(newBlock)) 1960 return failure(); 1961 region.push_back(newBlock); 1962 } 1963 return success(); 1964 } 1965 1966 //===----------------------------------------------------------------------===// 1967 // Block Parsing 1968 //===----------------------------------------------------------------------===// 1969 1970 /// Block declaration. 1971 /// 1972 /// block ::= block-label? operation* 1973 /// block-label ::= block-id block-arg-list? `:` 1974 /// block-id ::= caret-id 1975 /// block-arg-list ::= `(` ssa-id-and-type-list? `)` 1976 /// 1977 ParseResult OperationParser::parseBlock(Block *&block) { 1978 // The first block of a region may already exist, if it does the caret 1979 // identifier is optional. 1980 if (block && getToken().isNot(Token::caret_identifier)) 1981 return parseBlockBody(block); 1982 1983 SMLoc nameLoc = getToken().getLoc(); 1984 auto name = getTokenSpelling(); 1985 if (parseToken(Token::caret_identifier, "expected block name")) 1986 return failure(); 1987 1988 block = defineBlockNamed(name, nameLoc, block); 1989 1990 // Fail if the block was already defined. 1991 if (!block) 1992 return emitError(nameLoc, "redefinition of block '") << name << "'"; 1993 1994 // If an argument list is present, parse it. 1995 if (consumeIf(Token::l_paren)) { 1996 if (parseOptionalBlockArgList(block) || 1997 parseToken(Token::r_paren, "expected ')' to end argument list")) 1998 return failure(); 1999 } 2000 2001 if (parseToken(Token::colon, "expected ':' after block name")) 2002 return failure(); 2003 2004 return parseBlockBody(block); 2005 } 2006 2007 ParseResult OperationParser::parseBlockBody(Block *block) { 2008 // Set the insertion point to the end of the block to parse. 2009 opBuilder.setInsertionPointToEnd(block); 2010 2011 // Parse the list of operations that make up the body of the block. 2012 while (getToken().isNot(Token::caret_identifier, Token::r_brace)) 2013 if (parseOperation()) 2014 return failure(); 2015 2016 return success(); 2017 } 2018 2019 /// Get the block with the specified name, creating it if it doesn't already 2020 /// exist. The location specified is the point of use, which allows 2021 /// us to diagnose references to blocks that are not defined precisely. 2022 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) { 2023 BlockDefinition &blockDef = getBlockInfoByName(name); 2024 if (!blockDef.block) { 2025 blockDef = {new Block(), loc}; 2026 insertForwardRef(blockDef.block, blockDef.loc); 2027 } 2028 2029 // Populate the high level assembly state if necessary. 2030 if (state.asmState) 2031 state.asmState->addUses(blockDef.block, loc); 2032 2033 return blockDef.block; 2034 } 2035 2036 /// Define the block with the specified name. Returns the Block* or nullptr in 2037 /// the case of redefinition. 2038 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc, 2039 Block *existing) { 2040 auto &blockAndLoc = getBlockInfoByName(name); 2041 blockAndLoc.loc = loc; 2042 2043 // If a block has yet to be set, this is a new definition. If the caller 2044 // provided a block, use it. Otherwise create a new one. 2045 if (!blockAndLoc.block) { 2046 blockAndLoc.block = existing ? existing : new Block(); 2047 2048 // Otherwise, the block has a forward declaration. Forward declarations are 2049 // removed once defined, so if we are defining a existing block and it is 2050 // not a forward declaration, then it is a redeclaration. 2051 } else if (!eraseForwardRef(blockAndLoc.block)) { 2052 return nullptr; 2053 } 2054 2055 // Populate the high level assembly state if necessary. 2056 if (state.asmState) 2057 state.asmState->addDefinition(blockAndLoc.block, loc); 2058 2059 return blockAndLoc.block; 2060 } 2061 2062 /// Parse a (possibly empty) list of SSA operands with types as block arguments. 2063 /// 2064 /// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)* 2065 /// 2066 ParseResult OperationParser::parseOptionalBlockArgList(Block *owner) { 2067 if (getToken().is(Token::r_brace)) 2068 return success(); 2069 2070 // If the block already has arguments, then we're handling the entry block. 2071 // Parse and register the names for the arguments, but do not add them. 2072 bool definingExistingArgs = owner->getNumArguments() != 0; 2073 unsigned nextArgument = 0; 2074 2075 return parseCommaSeparatedList([&]() -> ParseResult { 2076 return parseSSADefOrUseAndType( 2077 [&](SSAUseInfo useInfo, Type type) -> ParseResult { 2078 BlockArgument arg; 2079 2080 // If we are defining existing arguments, ensure that the argument 2081 // has already been created with the right type. 2082 if (definingExistingArgs) { 2083 // Otherwise, ensure that this argument has already been created. 2084 if (nextArgument >= owner->getNumArguments()) 2085 return emitError("too many arguments specified in argument list"); 2086 2087 // Finally, make sure the existing argument has the correct type. 2088 arg = owner->getArgument(nextArgument++); 2089 if (arg.getType() != type) 2090 return emitError("argument and block argument type mismatch"); 2091 } else { 2092 arg = owner->addArgument(type); 2093 } 2094 2095 // Mark this block argument definition in the parser state if it was 2096 // provided. 2097 if (state.asmState) 2098 state.asmState->addDefinition(arg, useInfo.loc); 2099 2100 return addDefinition(useInfo, arg); 2101 }); 2102 }); 2103 } 2104 2105 //===----------------------------------------------------------------------===// 2106 // Top-level entity parsing. 2107 //===----------------------------------------------------------------------===// 2108 2109 namespace { 2110 /// This parser handles entities that are only valid at the top level of the 2111 /// file. 2112 class TopLevelOperationParser : public Parser { 2113 public: 2114 explicit TopLevelOperationParser(ParserState &state) : Parser(state) {} 2115 2116 /// Parse a set of operations into the end of the given Block. 2117 ParseResult parse(Block *topLevelBlock, Location parserLoc); 2118 2119 private: 2120 /// Parse an attribute alias declaration. 2121 ParseResult parseAttributeAliasDef(); 2122 2123 /// Parse an attribute alias declaration. 2124 ParseResult parseTypeAliasDef(); 2125 }; 2126 } // end anonymous namespace 2127 2128 /// Parses an attribute alias declaration. 2129 /// 2130 /// attribute-alias-def ::= '#' alias-name `=` attribute-value 2131 /// 2132 ParseResult TopLevelOperationParser::parseAttributeAliasDef() { 2133 assert(getToken().is(Token::hash_identifier)); 2134 StringRef aliasName = getTokenSpelling().drop_front(); 2135 2136 // Check for redefinitions. 2137 if (state.symbols.attributeAliasDefinitions.count(aliasName) > 0) 2138 return emitError("redefinition of attribute alias id '" + aliasName + "'"); 2139 2140 // Make sure this isn't invading the dialect attribute namespace. 2141 if (aliasName.contains('.')) 2142 return emitError("attribute names with a '.' are reserved for " 2143 "dialect-defined names"); 2144 2145 consumeToken(Token::hash_identifier); 2146 2147 // Parse the '='. 2148 if (parseToken(Token::equal, "expected '=' in attribute alias definition")) 2149 return failure(); 2150 2151 // Parse the attribute value. 2152 Attribute attr = parseAttribute(); 2153 if (!attr) 2154 return failure(); 2155 2156 state.symbols.attributeAliasDefinitions[aliasName] = attr; 2157 return success(); 2158 } 2159 2160 /// Parse a type alias declaration. 2161 /// 2162 /// type-alias-def ::= '!' alias-name `=` 'type' type 2163 /// 2164 ParseResult TopLevelOperationParser::parseTypeAliasDef() { 2165 assert(getToken().is(Token::exclamation_identifier)); 2166 StringRef aliasName = getTokenSpelling().drop_front(); 2167 2168 // Check for redefinitions. 2169 if (state.symbols.typeAliasDefinitions.count(aliasName) > 0) 2170 return emitError("redefinition of type alias id '" + aliasName + "'"); 2171 2172 // Make sure this isn't invading the dialect type namespace. 2173 if (aliasName.contains('.')) 2174 return emitError("type names with a '.' are reserved for " 2175 "dialect-defined names"); 2176 2177 consumeToken(Token::exclamation_identifier); 2178 2179 // Parse the '=' and 'type'. 2180 if (parseToken(Token::equal, "expected '=' in type alias definition") || 2181 parseToken(Token::kw_type, "expected 'type' in type alias definition")) 2182 return failure(); 2183 2184 // Parse the type. 2185 Type aliasedType = parseType(); 2186 if (!aliasedType) 2187 return failure(); 2188 2189 // Register this alias with the parser state. 2190 state.symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType); 2191 return success(); 2192 } 2193 2194 ParseResult TopLevelOperationParser::parse(Block *topLevelBlock, 2195 Location parserLoc) { 2196 // Create a top-level operation to contain the parsed state. 2197 OwningOpRef<Operation *> topLevelOp(ModuleOp::create(parserLoc)); 2198 OperationParser opParser(state, topLevelOp.get()); 2199 while (true) { 2200 switch (getToken().getKind()) { 2201 default: 2202 // Parse a top-level operation. 2203 if (opParser.parseOperation()) 2204 return failure(); 2205 break; 2206 2207 // If we got to the end of the file, then we're done. 2208 case Token::eof: { 2209 if (opParser.finalize()) 2210 return failure(); 2211 2212 // Verify that the parsed operations are valid. 2213 if (failed(verify(topLevelOp.get()))) 2214 return failure(); 2215 2216 // Splice the blocks of the parsed operation over to the provided 2217 // top-level block. 2218 auto &parsedOps = (*topLevelOp)->getRegion(0).front().getOperations(); 2219 auto &destOps = topLevelBlock->getOperations(); 2220 destOps.splice(destOps.empty() ? destOps.end() : std::prev(destOps.end()), 2221 parsedOps, parsedOps.begin(), parsedOps.end()); 2222 return success(); 2223 } 2224 2225 // If we got an error token, then the lexer already emitted an error, just 2226 // stop. Someday we could introduce error recovery if there was demand 2227 // for it. 2228 case Token::error: 2229 return failure(); 2230 2231 // Parse an attribute alias. 2232 case Token::hash_identifier: 2233 if (parseAttributeAliasDef()) 2234 return failure(); 2235 break; 2236 2237 // Parse a type alias. 2238 case Token::exclamation_identifier: 2239 if (parseTypeAliasDef()) 2240 return failure(); 2241 break; 2242 } 2243 } 2244 } 2245 2246 //===----------------------------------------------------------------------===// 2247 2248 LogicalResult mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr, 2249 Block *block, MLIRContext *context, 2250 LocationAttr *sourceFileLoc, 2251 AsmParserState *asmState) { 2252 const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID()); 2253 2254 Location parserLoc = FileLineColLoc::get( 2255 context, sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0); 2256 if (sourceFileLoc) 2257 *sourceFileLoc = parserLoc; 2258 2259 SymbolState aliasState; 2260 ParserState state(sourceMgr, context, aliasState, asmState); 2261 return TopLevelOperationParser(state).parse(block, parserLoc); 2262 } 2263 2264 LogicalResult mlir::parseSourceFile(llvm::StringRef filename, Block *block, 2265 MLIRContext *context, 2266 LocationAttr *sourceFileLoc) { 2267 llvm::SourceMgr sourceMgr; 2268 return parseSourceFile(filename, sourceMgr, block, context, sourceFileLoc); 2269 } 2270 2271 LogicalResult mlir::parseSourceFile(llvm::StringRef filename, 2272 llvm::SourceMgr &sourceMgr, Block *block, 2273 MLIRContext *context, 2274 LocationAttr *sourceFileLoc, 2275 AsmParserState *asmState) { 2276 if (sourceMgr.getNumBuffers() != 0) { 2277 // TODO: Extend to support multiple buffers. 2278 return emitError(mlir::UnknownLoc::get(context), 2279 "only main buffer parsed at the moment"); 2280 } 2281 auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename); 2282 if (std::error_code error = file_or_err.getError()) 2283 return emitError(mlir::UnknownLoc::get(context), 2284 "could not open input file " + filename); 2285 2286 // Load the MLIR source file. 2287 sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc()); 2288 return parseSourceFile(sourceMgr, block, context, sourceFileLoc, asmState); 2289 } 2290 2291 LogicalResult mlir::parseSourceString(llvm::StringRef sourceStr, Block *block, 2292 MLIRContext *context, 2293 LocationAttr *sourceFileLoc) { 2294 auto memBuffer = MemoryBuffer::getMemBuffer(sourceStr); 2295 if (!memBuffer) 2296 return failure(); 2297 2298 SourceMgr sourceMgr; 2299 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); 2300 return parseSourceFile(sourceMgr, block, context, sourceFileLoc); 2301 } 2302