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