1 //===- Operation.cpp - Operation support code -----------------------------===// 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 #include "mlir/IR/Operation.h" 10 #include "mlir/IR/BlockAndValueMapping.h" 11 #include "mlir/IR/BuiltinTypes.h" 12 #include "mlir/IR/Dialect.h" 13 #include "mlir/IR/OpImplementation.h" 14 #include "mlir/IR/PatternMatch.h" 15 #include "mlir/IR/TypeUtilities.h" 16 #include "mlir/Interfaces/FoldInterfaces.h" 17 #include <numeric> 18 19 using namespace mlir; 20 21 OpAsmParser::~OpAsmParser() {} 22 23 //===----------------------------------------------------------------------===// 24 // OperationName 25 //===----------------------------------------------------------------------===// 26 27 /// Form the OperationName for an op with the specified string. This either is 28 /// a reference to an AbstractOperation if one is known, or a uniqued Identifier 29 /// if not. 30 OperationName::OperationName(StringRef name, MLIRContext *context) { 31 if (auto *op = AbstractOperation::lookup(name, context)) 32 representation = op; 33 else 34 representation = Identifier::get(name, context); 35 } 36 37 /// Return the name of the dialect this operation is registered to. 38 StringRef OperationName::getDialectNamespace() const { 39 if (Dialect *dialect = getDialect()) 40 return dialect->getNamespace(); 41 return representation.get<Identifier>().strref().split('.').first; 42 } 43 44 /// Return the operation name with dialect name stripped, if it has one. 45 StringRef OperationName::stripDialect() const { 46 auto splitName = getStringRef().split("."); 47 return splitName.second.empty() ? splitName.first : splitName.second; 48 } 49 50 /// Return the name of this operation. This always succeeds. 51 StringRef OperationName::getStringRef() const { 52 return getIdentifier().strref(); 53 } 54 55 /// Return the name of this operation as an identifier. This always succeeds. 56 Identifier OperationName::getIdentifier() const { 57 if (auto *op = representation.dyn_cast<const AbstractOperation *>()) 58 return op->name; 59 return representation.get<Identifier>(); 60 } 61 62 OperationName OperationName::getFromOpaquePointer(const void *pointer) { 63 return OperationName( 64 RepresentationUnion::getFromOpaqueValue(const_cast<void *>(pointer))); 65 } 66 67 //===----------------------------------------------------------------------===// 68 // Operation 69 //===----------------------------------------------------------------------===// 70 71 /// Create a new Operation with the specific fields. 72 Operation *Operation::create(Location location, OperationName name, 73 TypeRange resultTypes, ValueRange operands, 74 ArrayRef<NamedAttribute> attributes, 75 BlockRange successors, unsigned numRegions) { 76 return create(location, name, resultTypes, operands, 77 DictionaryAttr::get(location.getContext(), attributes), 78 successors, numRegions); 79 } 80 81 /// Create a new Operation from operation state. 82 Operation *Operation::create(const OperationState &state) { 83 return create(state.location, state.name, state.types, state.operands, 84 state.attributes.getDictionary(state.getContext()), 85 state.successors, state.regions); 86 } 87 88 /// Create a new Operation with the specific fields. 89 Operation *Operation::create(Location location, OperationName name, 90 TypeRange resultTypes, ValueRange operands, 91 DictionaryAttr attributes, BlockRange successors, 92 RegionRange regions) { 93 unsigned numRegions = regions.size(); 94 Operation *op = create(location, name, resultTypes, operands, attributes, 95 successors, numRegions); 96 for (unsigned i = 0; i < numRegions; ++i) 97 if (regions[i]) 98 op->getRegion(i).takeBody(*regions[i]); 99 return op; 100 } 101 102 /// Overload of create that takes an existing DictionaryAttr to avoid 103 /// unnecessarily uniquing a list of attributes. 104 Operation *Operation::create(Location location, OperationName name, 105 TypeRange resultTypes, ValueRange operands, 106 DictionaryAttr attributes, BlockRange successors, 107 unsigned numRegions) { 108 assert(llvm::all_of(resultTypes, [](Type t) { return t; }) && 109 "unexpected null result type"); 110 111 // We only need to allocate additional memory for a subset of results. 112 unsigned numTrailingResults = OpResult::getNumTrailing(resultTypes.size()); 113 unsigned numInlineResults = OpResult::getNumInline(resultTypes.size()); 114 unsigned numSuccessors = successors.size(); 115 unsigned numOperands = operands.size(); 116 unsigned numResults = resultTypes.size(); 117 118 // If the operation is known to have no operands, don't allocate an operand 119 // storage. 120 bool needsOperandStorage = true; 121 if (operands.empty()) { 122 if (const AbstractOperation *abstractOp = name.getAbstractOperation()) 123 needsOperandStorage = !abstractOp->hasTrait<OpTrait::ZeroOperands>(); 124 } 125 126 // Compute the byte size for the operation and the operand storage. This takes 127 // into account the size of the operation, its trailing objects, and its 128 // prefixed objects. 129 size_t byteSize = 130 totalSizeToAlloc<BlockOperand, Region, detail::OperandStorage>( 131 numSuccessors, numRegions, needsOperandStorage ? 1 : 0) + 132 detail::OperandStorage::additionalAllocSize(numOperands); 133 size_t prefixByteSize = llvm::alignTo( 134 Operation::prefixAllocSize(numTrailingResults, numInlineResults), 135 alignof(Operation)); 136 char *mallocMem = reinterpret_cast<char *>(malloc(byteSize + prefixByteSize)); 137 void *rawMem = mallocMem + prefixByteSize; 138 139 // Create the new Operation. 140 Operation *op = 141 ::new (rawMem) Operation(location, name, numResults, numSuccessors, 142 numRegions, attributes, needsOperandStorage); 143 144 assert((numSuccessors == 0 || op->mightHaveTrait<OpTrait::IsTerminator>()) && 145 "unexpected successors in a non-terminator operation"); 146 147 // Initialize the results. 148 auto resultTypeIt = resultTypes.begin(); 149 for (unsigned i = 0; i < numInlineResults; ++i, ++resultTypeIt) 150 new (op->getInlineOpResult(i)) detail::InlineOpResult(*resultTypeIt, i); 151 for (unsigned i = 0; i < numTrailingResults; ++i, ++resultTypeIt) { 152 new (op->getOutOfLineOpResult(i)) 153 detail::OutOfLineOpResult(*resultTypeIt, i); 154 } 155 156 // Initialize the regions. 157 for (unsigned i = 0; i != numRegions; ++i) 158 new (&op->getRegion(i)) Region(op); 159 160 // Initialize the operands. 161 if (needsOperandStorage) 162 new (&op->getOperandStorage()) detail::OperandStorage(op, operands); 163 164 // Initialize the successors. 165 auto blockOperands = op->getBlockOperands(); 166 for (unsigned i = 0; i != numSuccessors; ++i) 167 new (&blockOperands[i]) BlockOperand(op, successors[i]); 168 169 return op; 170 } 171 172 Operation::Operation(Location location, OperationName name, unsigned numResults, 173 unsigned numSuccessors, unsigned numRegions, 174 DictionaryAttr attributes, bool hasOperandStorage) 175 : location(location), numResults(numResults), numSuccs(numSuccessors), 176 numRegions(numRegions), hasOperandStorage(hasOperandStorage), name(name), 177 attrs(attributes) { 178 assert(attributes && "unexpected null attribute dictionary"); 179 #ifndef NDEBUG 180 if (!getDialect() && !getContext()->allowsUnregisteredDialects()) 181 llvm::report_fatal_error( 182 name.getStringRef() + 183 " created with unregistered dialect. If this is intended, please call " 184 "allowUnregisteredDialects() on the MLIRContext, or use " 185 "-allow-unregistered-dialect with the MLIR opt tool used"); 186 #endif 187 } 188 189 // Operations are deleted through the destroy() member because they are 190 // allocated via malloc. 191 Operation::~Operation() { 192 assert(block == nullptr && "operation destroyed but still in a block"); 193 #ifndef NDEBUG 194 if (!use_empty()) { 195 { 196 InFlightDiagnostic diag = 197 emitOpError("operation destroyed but still has uses"); 198 for (Operation *user : getUsers()) 199 diag.attachNote(user->getLoc()) << "- use: " << *user << "\n"; 200 } 201 llvm::report_fatal_error("operation destroyed but still has uses"); 202 } 203 #endif 204 // Explicitly run the destructors for the operands. 205 if (hasOperandStorage) 206 getOperandStorage().~OperandStorage(); 207 208 // Explicitly run the destructors for the successors. 209 for (auto &successor : getBlockOperands()) 210 successor.~BlockOperand(); 211 212 // Explicitly destroy the regions. 213 for (auto ®ion : getRegions()) 214 region.~Region(); 215 } 216 217 /// Destroy this operation or one of its subclasses. 218 void Operation::destroy() { 219 // Operations may have additional prefixed allocation, which needs to be 220 // accounted for here when computing the address to free. 221 char *rawMem = reinterpret_cast<char *>(this) - 222 llvm::alignTo(prefixAllocSize(), alignof(Operation)); 223 this->~Operation(); 224 free(rawMem); 225 } 226 227 /// Return true if this operation is a proper ancestor of the `other` 228 /// operation. 229 bool Operation::isProperAncestor(Operation *other) { 230 while ((other = other->getParentOp())) 231 if (this == other) 232 return true; 233 return false; 234 } 235 236 /// Replace any uses of 'from' with 'to' within this operation. 237 void Operation::replaceUsesOfWith(Value from, Value to) { 238 if (from == to) 239 return; 240 for (auto &operand : getOpOperands()) 241 if (operand.get() == from) 242 operand.set(to); 243 } 244 245 /// Replace the current operands of this operation with the ones provided in 246 /// 'operands'. 247 void Operation::setOperands(ValueRange operands) { 248 if (LLVM_LIKELY(hasOperandStorage)) 249 return getOperandStorage().setOperands(this, operands); 250 assert(operands.empty() && "setting operands without an operand storage"); 251 } 252 253 /// Replace the operands beginning at 'start' and ending at 'start' + 'length' 254 /// with the ones provided in 'operands'. 'operands' may be smaller or larger 255 /// than the range pointed to by 'start'+'length'. 256 void Operation::setOperands(unsigned start, unsigned length, 257 ValueRange operands) { 258 assert((start + length) <= getNumOperands() && 259 "invalid operand range specified"); 260 if (LLVM_LIKELY(hasOperandStorage)) 261 return getOperandStorage().setOperands(this, start, length, operands); 262 assert(operands.empty() && "setting operands without an operand storage"); 263 } 264 265 /// Insert the given operands into the operand list at the given 'index'. 266 void Operation::insertOperands(unsigned index, ValueRange operands) { 267 if (LLVM_LIKELY(hasOperandStorage)) 268 return setOperands(index, /*length=*/0, operands); 269 assert(operands.empty() && "inserting operands without an operand storage"); 270 } 271 272 //===----------------------------------------------------------------------===// 273 // Diagnostics 274 //===----------------------------------------------------------------------===// 275 276 /// Emit an error about fatal conditions with this operation, reporting up to 277 /// any diagnostic handlers that may be listening. 278 InFlightDiagnostic Operation::emitError(const Twine &message) { 279 InFlightDiagnostic diag = mlir::emitError(getLoc(), message); 280 if (getContext()->shouldPrintOpOnDiagnostic()) { 281 // Print out the operation explicitly here so that we can print the generic 282 // form. 283 // TODO: It would be nice if we could instead provide the 284 // specific printing flags when adding the operation as an argument to the 285 // diagnostic. 286 std::string printedOp; 287 { 288 llvm::raw_string_ostream os(printedOp); 289 print(os, OpPrintingFlags().printGenericOpForm().useLocalScope()); 290 } 291 diag.attachNote(getLoc()) << "see current operation: " << printedOp; 292 } 293 return diag; 294 } 295 296 /// Emit a warning about this operation, reporting up to any diagnostic 297 /// handlers that may be listening. 298 InFlightDiagnostic Operation::emitWarning(const Twine &message) { 299 InFlightDiagnostic diag = mlir::emitWarning(getLoc(), message); 300 if (getContext()->shouldPrintOpOnDiagnostic()) 301 diag.attachNote(getLoc()) << "see current operation: " << *this; 302 return diag; 303 } 304 305 /// Emit a remark about this operation, reporting up to any diagnostic 306 /// handlers that may be listening. 307 InFlightDiagnostic Operation::emitRemark(const Twine &message) { 308 InFlightDiagnostic diag = mlir::emitRemark(getLoc(), message); 309 if (getContext()->shouldPrintOpOnDiagnostic()) 310 diag.attachNote(getLoc()) << "see current operation: " << *this; 311 return diag; 312 } 313 314 //===----------------------------------------------------------------------===// 315 // Operation Ordering 316 //===----------------------------------------------------------------------===// 317 318 constexpr unsigned Operation::kInvalidOrderIdx; 319 constexpr unsigned Operation::kOrderStride; 320 321 /// Given an operation 'other' that is within the same parent block, return 322 /// whether the current operation is before 'other' in the operation list 323 /// of the parent block. 324 /// Note: This function has an average complexity of O(1), but worst case may 325 /// take O(N) where N is the number of operations within the parent block. 326 bool Operation::isBeforeInBlock(Operation *other) { 327 assert(block && "Operations without parent blocks have no order."); 328 assert(other && other->block == block && 329 "Expected other operation to have the same parent block."); 330 // If the order of the block is already invalid, directly recompute the 331 // parent. 332 if (!block->isOpOrderValid()) { 333 block->recomputeOpOrder(); 334 } else { 335 // Update the order either operation if necessary. 336 updateOrderIfNecessary(); 337 other->updateOrderIfNecessary(); 338 } 339 340 return orderIndex < other->orderIndex; 341 } 342 343 /// Update the order index of this operation of this operation if necessary, 344 /// potentially recomputing the order of the parent block. 345 void Operation::updateOrderIfNecessary() { 346 assert(block && "expected valid parent"); 347 348 // If the order is valid for this operation there is nothing to do. 349 if (hasValidOrder()) 350 return; 351 Operation *blockFront = &block->front(); 352 Operation *blockBack = &block->back(); 353 354 // This method is expected to only be invoked on blocks with more than one 355 // operation. 356 assert(blockFront != blockBack && "expected more than one operation"); 357 358 // If the operation is at the end of the block. 359 if (this == blockBack) { 360 Operation *prevNode = getPrevNode(); 361 if (!prevNode->hasValidOrder()) 362 return block->recomputeOpOrder(); 363 364 // Add the stride to the previous operation. 365 orderIndex = prevNode->orderIndex + kOrderStride; 366 return; 367 } 368 369 // If this is the first operation try to use the next operation to compute the 370 // ordering. 371 if (this == blockFront) { 372 Operation *nextNode = getNextNode(); 373 if (!nextNode->hasValidOrder()) 374 return block->recomputeOpOrder(); 375 // There is no order to give this operation. 376 if (nextNode->orderIndex == 0) 377 return block->recomputeOpOrder(); 378 379 // If we can't use the stride, just take the middle value left. This is safe 380 // because we know there is at least one valid index to assign to. 381 if (nextNode->orderIndex <= kOrderStride) 382 orderIndex = (nextNode->orderIndex / 2); 383 else 384 orderIndex = kOrderStride; 385 return; 386 } 387 388 // Otherwise, this operation is between two others. Place this operation in 389 // the middle of the previous and next if possible. 390 Operation *prevNode = getPrevNode(), *nextNode = getNextNode(); 391 if (!prevNode->hasValidOrder() || !nextNode->hasValidOrder()) 392 return block->recomputeOpOrder(); 393 unsigned prevOrder = prevNode->orderIndex, nextOrder = nextNode->orderIndex; 394 395 // Check to see if there is a valid order between the two. 396 if (prevOrder + 1 == nextOrder) 397 return block->recomputeOpOrder(); 398 orderIndex = prevOrder + ((nextOrder - prevOrder) / 2); 399 } 400 401 //===----------------------------------------------------------------------===// 402 // ilist_traits for Operation 403 //===----------------------------------------------------------------------===// 404 405 auto llvm::ilist_detail::SpecificNodeAccess< 406 typename llvm::ilist_detail::compute_node_options< 407 ::mlir::Operation>::type>::getNodePtr(pointer N) -> node_type * { 408 return NodeAccess::getNodePtr<OptionsT>(N); 409 } 410 411 auto llvm::ilist_detail::SpecificNodeAccess< 412 typename llvm::ilist_detail::compute_node_options< 413 ::mlir::Operation>::type>::getNodePtr(const_pointer N) 414 -> const node_type * { 415 return NodeAccess::getNodePtr<OptionsT>(N); 416 } 417 418 auto llvm::ilist_detail::SpecificNodeAccess< 419 typename llvm::ilist_detail::compute_node_options< 420 ::mlir::Operation>::type>::getValuePtr(node_type *N) -> pointer { 421 return NodeAccess::getValuePtr<OptionsT>(N); 422 } 423 424 auto llvm::ilist_detail::SpecificNodeAccess< 425 typename llvm::ilist_detail::compute_node_options< 426 ::mlir::Operation>::type>::getValuePtr(const node_type *N) 427 -> const_pointer { 428 return NodeAccess::getValuePtr<OptionsT>(N); 429 } 430 431 void llvm::ilist_traits<::mlir::Operation>::deleteNode(Operation *op) { 432 op->destroy(); 433 } 434 435 Block *llvm::ilist_traits<::mlir::Operation>::getContainingBlock() { 436 size_t Offset(size_t(&((Block *)nullptr->*Block::getSublistAccess(nullptr)))); 437 iplist<Operation> *Anchor(static_cast<iplist<Operation> *>(this)); 438 return reinterpret_cast<Block *>(reinterpret_cast<char *>(Anchor) - Offset); 439 } 440 441 /// This is a trait method invoked when an operation is added to a block. We 442 /// keep the block pointer up to date. 443 void llvm::ilist_traits<::mlir::Operation>::addNodeToList(Operation *op) { 444 assert(!op->getBlock() && "already in an operation block!"); 445 op->block = getContainingBlock(); 446 447 // Invalidate the order on the operation. 448 op->orderIndex = Operation::kInvalidOrderIdx; 449 } 450 451 /// This is a trait method invoked when an operation is removed from a block. 452 /// We keep the block pointer up to date. 453 void llvm::ilist_traits<::mlir::Operation>::removeNodeFromList(Operation *op) { 454 assert(op->block && "not already in an operation block!"); 455 op->block = nullptr; 456 } 457 458 /// This is a trait method invoked when an operation is moved from one block 459 /// to another. We keep the block pointer up to date. 460 void llvm::ilist_traits<::mlir::Operation>::transferNodesFromList( 461 ilist_traits<Operation> &otherList, op_iterator first, op_iterator last) { 462 Block *curParent = getContainingBlock(); 463 464 // Invalidate the ordering of the parent block. 465 curParent->invalidateOpOrder(); 466 467 // If we are transferring operations within the same block, the block 468 // pointer doesn't need to be updated. 469 if (curParent == otherList.getContainingBlock()) 470 return; 471 472 // Update the 'block' member of each operation. 473 for (; first != last; ++first) 474 first->block = curParent; 475 } 476 477 /// Remove this operation (and its descendants) from its Block and delete 478 /// all of them. 479 void Operation::erase() { 480 if (auto *parent = getBlock()) 481 parent->getOperations().erase(this); 482 else 483 destroy(); 484 } 485 486 /// Remove the operation from its parent block, but don't delete it. 487 void Operation::remove() { 488 if (Block *parent = getBlock()) 489 parent->getOperations().remove(this); 490 } 491 492 /// Unlink this operation from its current block and insert it right before 493 /// `existingOp` which may be in the same or another block in the same 494 /// function. 495 void Operation::moveBefore(Operation *existingOp) { 496 moveBefore(existingOp->getBlock(), existingOp->getIterator()); 497 } 498 499 /// Unlink this operation from its current basic block and insert it right 500 /// before `iterator` in the specified basic block. 501 void Operation::moveBefore(Block *block, 502 llvm::iplist<Operation>::iterator iterator) { 503 block->getOperations().splice(iterator, getBlock()->getOperations(), 504 getIterator()); 505 } 506 507 /// Unlink this operation from its current block and insert it right after 508 /// `existingOp` which may be in the same or another block in the same function. 509 void Operation::moveAfter(Operation *existingOp) { 510 moveAfter(existingOp->getBlock(), existingOp->getIterator()); 511 } 512 513 /// Unlink this operation from its current block and insert it right after 514 /// `iterator` in the specified block. 515 void Operation::moveAfter(Block *block, 516 llvm::iplist<Operation>::iterator iterator) { 517 assert(iterator != block->end() && "cannot move after end of block"); 518 moveBefore(&*std::next(iterator)); 519 } 520 521 /// This drops all operand uses from this operation, which is an essential 522 /// step in breaking cyclic dependences between references when they are to 523 /// be deleted. 524 void Operation::dropAllReferences() { 525 for (auto &op : getOpOperands()) 526 op.drop(); 527 528 for (auto ®ion : getRegions()) 529 region.dropAllReferences(); 530 531 for (auto &dest : getBlockOperands()) 532 dest.drop(); 533 } 534 535 /// This drops all uses of any values defined by this operation or its nested 536 /// regions, wherever they are located. 537 void Operation::dropAllDefinedValueUses() { 538 dropAllUses(); 539 540 for (auto ®ion : getRegions()) 541 for (auto &block : region) 542 block.dropAllDefinedValueUses(); 543 } 544 545 void Operation::setSuccessor(Block *block, unsigned index) { 546 assert(index < getNumSuccessors()); 547 getBlockOperands()[index].set(block); 548 } 549 550 /// Attempt to fold this operation using the Op's registered foldHook. 551 LogicalResult Operation::fold(ArrayRef<Attribute> operands, 552 SmallVectorImpl<OpFoldResult> &results) { 553 // If we have a registered operation definition matching this one, use it to 554 // try to constant fold the operation. 555 auto *abstractOp = getAbstractOperation(); 556 if (abstractOp && succeeded(abstractOp->foldHook(this, operands, results))) 557 return success(); 558 559 // Otherwise, fall back on the dialect hook to handle it. 560 Dialect *dialect = getDialect(); 561 if (!dialect) 562 return failure(); 563 564 auto *interface = dialect->getRegisteredInterface<DialectFoldInterface>(); 565 if (!interface) 566 return failure(); 567 568 return interface->fold(this, operands, results); 569 } 570 571 /// Emit an error with the op name prefixed, like "'dim' op " which is 572 /// convenient for verifiers. 573 InFlightDiagnostic Operation::emitOpError(const Twine &message) { 574 return emitError() << "'" << getName() << "' op " << message; 575 } 576 577 //===----------------------------------------------------------------------===// 578 // Operation Cloning 579 //===----------------------------------------------------------------------===// 580 581 /// Create a deep copy of this operation but keep the operation regions empty. 582 /// Operands are remapped using `mapper` (if present), and `mapper` is updated 583 /// to contain the results. 584 Operation *Operation::cloneWithoutRegions(BlockAndValueMapping &mapper) { 585 SmallVector<Value, 8> operands; 586 SmallVector<Block *, 2> successors; 587 588 // Remap the operands. 589 operands.reserve(getNumOperands()); 590 for (auto opValue : getOperands()) 591 operands.push_back(mapper.lookupOrDefault(opValue)); 592 593 // Remap the successors. 594 successors.reserve(getNumSuccessors()); 595 for (Block *successor : getSuccessors()) 596 successors.push_back(mapper.lookupOrDefault(successor)); 597 598 // Create the new operation. 599 auto *newOp = create(getLoc(), getName(), getResultTypes(), operands, attrs, 600 successors, getNumRegions()); 601 602 // Remember the mapping of any results. 603 for (unsigned i = 0, e = getNumResults(); i != e; ++i) 604 mapper.map(getResult(i), newOp->getResult(i)); 605 606 return newOp; 607 } 608 609 Operation *Operation::cloneWithoutRegions() { 610 BlockAndValueMapping mapper; 611 return cloneWithoutRegions(mapper); 612 } 613 614 /// Create a deep copy of this operation, remapping any operands that use 615 /// values outside of the operation using the map that is provided (leaving 616 /// them alone if no entry is present). Replaces references to cloned 617 /// sub-operations to the corresponding operation that is copied, and adds 618 /// those mappings to the map. 619 Operation *Operation::clone(BlockAndValueMapping &mapper) { 620 auto *newOp = cloneWithoutRegions(mapper); 621 622 // Clone the regions. 623 for (unsigned i = 0; i != numRegions; ++i) 624 getRegion(i).cloneInto(&newOp->getRegion(i), mapper); 625 626 return newOp; 627 } 628 629 Operation *Operation::clone() { 630 BlockAndValueMapping mapper; 631 return clone(mapper); 632 } 633 634 //===----------------------------------------------------------------------===// 635 // OpState trait class. 636 //===----------------------------------------------------------------------===// 637 638 // The fallback for the parser is to reject the custom assembly form. 639 ParseResult OpState::parse(OpAsmParser &parser, OperationState &result) { 640 return parser.emitError(parser.getNameLoc(), "has no custom assembly form"); 641 } 642 643 // The fallback for the printer is to print in the generic assembly form. 644 void OpState::print(Operation *op, OpAsmPrinter &p) { p.printGenericOp(op); } 645 646 /// Emit an error about fatal conditions with this operation, reporting up to 647 /// any diagnostic handlers that may be listening. 648 InFlightDiagnostic OpState::emitError(const Twine &message) { 649 return getOperation()->emitError(message); 650 } 651 652 /// Emit an error with the op name prefixed, like "'dim' op " which is 653 /// convenient for verifiers. 654 InFlightDiagnostic OpState::emitOpError(const Twine &message) { 655 return getOperation()->emitOpError(message); 656 } 657 658 /// Emit a warning about this operation, reporting up to any diagnostic 659 /// handlers that may be listening. 660 InFlightDiagnostic OpState::emitWarning(const Twine &message) { 661 return getOperation()->emitWarning(message); 662 } 663 664 /// Emit a remark about this operation, reporting up to any diagnostic 665 /// handlers that may be listening. 666 InFlightDiagnostic OpState::emitRemark(const Twine &message) { 667 return getOperation()->emitRemark(message); 668 } 669 670 //===----------------------------------------------------------------------===// 671 // Op Trait implementations 672 //===----------------------------------------------------------------------===// 673 674 OpFoldResult OpTrait::impl::foldIdempotent(Operation *op) { 675 auto *argumentOp = op->getOperand(0).getDefiningOp(); 676 if (argumentOp && op->getName() == argumentOp->getName()) { 677 // Replace the outer operation output with the inner operation. 678 return op->getOperand(0); 679 } 680 681 return {}; 682 } 683 684 OpFoldResult OpTrait::impl::foldInvolution(Operation *op) { 685 auto *argumentOp = op->getOperand(0).getDefiningOp(); 686 if (argumentOp && op->getName() == argumentOp->getName()) { 687 // Replace the outer involutions output with inner's input. 688 return argumentOp->getOperand(0); 689 } 690 691 return {}; 692 } 693 694 LogicalResult OpTrait::impl::verifyZeroOperands(Operation *op) { 695 if (op->getNumOperands() != 0) 696 return op->emitOpError() << "requires zero operands"; 697 return success(); 698 } 699 700 LogicalResult OpTrait::impl::verifyOneOperand(Operation *op) { 701 if (op->getNumOperands() != 1) 702 return op->emitOpError() << "requires a single operand"; 703 return success(); 704 } 705 706 LogicalResult OpTrait::impl::verifyNOperands(Operation *op, 707 unsigned numOperands) { 708 if (op->getNumOperands() != numOperands) { 709 return op->emitOpError() << "expected " << numOperands 710 << " operands, but found " << op->getNumOperands(); 711 } 712 return success(); 713 } 714 715 LogicalResult OpTrait::impl::verifyAtLeastNOperands(Operation *op, 716 unsigned numOperands) { 717 if (op->getNumOperands() < numOperands) 718 return op->emitOpError() 719 << "expected " << numOperands << " or more operands"; 720 return success(); 721 } 722 723 /// If this is a vector type, or a tensor type, return the scalar element type 724 /// that it is built around, otherwise return the type unmodified. 725 static Type getTensorOrVectorElementType(Type type) { 726 if (auto vec = type.dyn_cast<VectorType>()) 727 return vec.getElementType(); 728 729 // Look through tensor<vector<...>> to find the underlying element type. 730 if (auto tensor = type.dyn_cast<TensorType>()) 731 return getTensorOrVectorElementType(tensor.getElementType()); 732 return type; 733 } 734 735 LogicalResult OpTrait::impl::verifyIsIdempotent(Operation *op) { 736 // FIXME: Add back check for no side effects on operation. 737 // Currently adding it would cause the shared library build 738 // to fail since there would be a dependency of IR on SideEffectInterfaces 739 // which is cyclical. 740 return success(); 741 } 742 743 LogicalResult OpTrait::impl::verifyIsInvolution(Operation *op) { 744 // FIXME: Add back check for no side effects on operation. 745 // Currently adding it would cause the shared library build 746 // to fail since there would be a dependency of IR on SideEffectInterfaces 747 // which is cyclical. 748 return success(); 749 } 750 751 LogicalResult 752 OpTrait::impl::verifyOperandsAreSignlessIntegerLike(Operation *op) { 753 for (auto opType : op->getOperandTypes()) { 754 auto type = getTensorOrVectorElementType(opType); 755 if (!type.isSignlessIntOrIndex()) 756 return op->emitOpError() << "requires an integer or index type"; 757 } 758 return success(); 759 } 760 761 LogicalResult OpTrait::impl::verifyOperandsAreFloatLike(Operation *op) { 762 for (auto opType : op->getOperandTypes()) { 763 auto type = getTensorOrVectorElementType(opType); 764 if (!type.isa<FloatType>()) 765 return op->emitOpError("requires a float type"); 766 } 767 return success(); 768 } 769 770 LogicalResult OpTrait::impl::verifySameTypeOperands(Operation *op) { 771 // Zero or one operand always have the "same" type. 772 unsigned nOperands = op->getNumOperands(); 773 if (nOperands < 2) 774 return success(); 775 776 auto type = op->getOperand(0).getType(); 777 for (auto opType : llvm::drop_begin(op->getOperandTypes(), 1)) 778 if (opType != type) 779 return op->emitOpError() << "requires all operands to have the same type"; 780 return success(); 781 } 782 783 LogicalResult OpTrait::impl::verifyZeroRegion(Operation *op) { 784 if (op->getNumRegions() != 0) 785 return op->emitOpError() << "requires zero regions"; 786 return success(); 787 } 788 789 LogicalResult OpTrait::impl::verifyOneRegion(Operation *op) { 790 if (op->getNumRegions() != 1) 791 return op->emitOpError() << "requires one region"; 792 return success(); 793 } 794 795 LogicalResult OpTrait::impl::verifyNRegions(Operation *op, 796 unsigned numRegions) { 797 if (op->getNumRegions() != numRegions) 798 return op->emitOpError() << "expected " << numRegions << " regions"; 799 return success(); 800 } 801 802 LogicalResult OpTrait::impl::verifyAtLeastNRegions(Operation *op, 803 unsigned numRegions) { 804 if (op->getNumRegions() < numRegions) 805 return op->emitOpError() << "expected " << numRegions << " or more regions"; 806 return success(); 807 } 808 809 LogicalResult OpTrait::impl::verifyZeroResult(Operation *op) { 810 if (op->getNumResults() != 0) 811 return op->emitOpError() << "requires zero results"; 812 return success(); 813 } 814 815 LogicalResult OpTrait::impl::verifyOneResult(Operation *op) { 816 if (op->getNumResults() != 1) 817 return op->emitOpError() << "requires one result"; 818 return success(); 819 } 820 821 LogicalResult OpTrait::impl::verifyNResults(Operation *op, 822 unsigned numOperands) { 823 if (op->getNumResults() != numOperands) 824 return op->emitOpError() << "expected " << numOperands << " results"; 825 return success(); 826 } 827 828 LogicalResult OpTrait::impl::verifyAtLeastNResults(Operation *op, 829 unsigned numOperands) { 830 if (op->getNumResults() < numOperands) 831 return op->emitOpError() 832 << "expected " << numOperands << " or more results"; 833 return success(); 834 } 835 836 LogicalResult OpTrait::impl::verifySameOperandsShape(Operation *op) { 837 if (failed(verifyAtLeastNOperands(op, 1))) 838 return failure(); 839 840 if (failed(verifyCompatibleShapes(op->getOperandTypes()))) 841 return op->emitOpError() << "requires the same shape for all operands"; 842 843 return success(); 844 } 845 846 LogicalResult OpTrait::impl::verifySameOperandsAndResultShape(Operation *op) { 847 if (failed(verifyAtLeastNOperands(op, 1)) || 848 failed(verifyAtLeastNResults(op, 1))) 849 return failure(); 850 851 SmallVector<Type, 8> types(op->getOperandTypes()); 852 types.append(llvm::to_vector<4>(op->getResultTypes())); 853 854 if (failed(verifyCompatibleShapes(types))) 855 return op->emitOpError() 856 << "requires the same shape for all operands and results"; 857 858 return success(); 859 } 860 861 LogicalResult OpTrait::impl::verifySameOperandsElementType(Operation *op) { 862 if (failed(verifyAtLeastNOperands(op, 1))) 863 return failure(); 864 auto elementType = getElementTypeOrSelf(op->getOperand(0)); 865 866 for (auto operand : llvm::drop_begin(op->getOperands(), 1)) { 867 if (getElementTypeOrSelf(operand) != elementType) 868 return op->emitOpError("requires the same element type for all operands"); 869 } 870 871 return success(); 872 } 873 874 LogicalResult 875 OpTrait::impl::verifySameOperandsAndResultElementType(Operation *op) { 876 if (failed(verifyAtLeastNOperands(op, 1)) || 877 failed(verifyAtLeastNResults(op, 1))) 878 return failure(); 879 880 auto elementType = getElementTypeOrSelf(op->getResult(0)); 881 882 // Verify result element type matches first result's element type. 883 for (auto result : llvm::drop_begin(op->getResults(), 1)) { 884 if (getElementTypeOrSelf(result) != elementType) 885 return op->emitOpError( 886 "requires the same element type for all operands and results"); 887 } 888 889 // Verify operand's element type matches first result's element type. 890 for (auto operand : op->getOperands()) { 891 if (getElementTypeOrSelf(operand) != elementType) 892 return op->emitOpError( 893 "requires the same element type for all operands and results"); 894 } 895 896 return success(); 897 } 898 899 LogicalResult OpTrait::impl::verifySameOperandsAndResultType(Operation *op) { 900 if (failed(verifyAtLeastNOperands(op, 1)) || 901 failed(verifyAtLeastNResults(op, 1))) 902 return failure(); 903 904 auto type = op->getResult(0).getType(); 905 auto elementType = getElementTypeOrSelf(type); 906 for (auto resultType : llvm::drop_begin(op->getResultTypes())) { 907 if (getElementTypeOrSelf(resultType) != elementType || 908 failed(verifyCompatibleShape(resultType, type))) 909 return op->emitOpError() 910 << "requires the same type for all operands and results"; 911 } 912 for (auto opType : op->getOperandTypes()) { 913 if (getElementTypeOrSelf(opType) != elementType || 914 failed(verifyCompatibleShape(opType, type))) 915 return op->emitOpError() 916 << "requires the same type for all operands and results"; 917 } 918 return success(); 919 } 920 921 LogicalResult OpTrait::impl::verifyIsTerminator(Operation *op) { 922 Block *block = op->getBlock(); 923 // Verify that the operation is at the end of the respective parent block. 924 if (!block || &block->back() != op) 925 return op->emitOpError("must be the last operation in the parent block"); 926 return success(); 927 } 928 929 static LogicalResult verifyTerminatorSuccessors(Operation *op) { 930 auto *parent = op->getParentRegion(); 931 932 // Verify that the operands lines up with the BB arguments in the successor. 933 for (Block *succ : op->getSuccessors()) 934 if (succ->getParent() != parent) 935 return op->emitError("reference to block defined in another region"); 936 return success(); 937 } 938 939 LogicalResult OpTrait::impl::verifyZeroSuccessor(Operation *op) { 940 if (op->getNumSuccessors() != 0) { 941 return op->emitOpError("requires 0 successors but found ") 942 << op->getNumSuccessors(); 943 } 944 return success(); 945 } 946 947 LogicalResult OpTrait::impl::verifyOneSuccessor(Operation *op) { 948 if (op->getNumSuccessors() != 1) { 949 return op->emitOpError("requires 1 successor but found ") 950 << op->getNumSuccessors(); 951 } 952 return verifyTerminatorSuccessors(op); 953 } 954 LogicalResult OpTrait::impl::verifyNSuccessors(Operation *op, 955 unsigned numSuccessors) { 956 if (op->getNumSuccessors() != numSuccessors) { 957 return op->emitOpError("requires ") 958 << numSuccessors << " successors but found " 959 << op->getNumSuccessors(); 960 } 961 return verifyTerminatorSuccessors(op); 962 } 963 LogicalResult OpTrait::impl::verifyAtLeastNSuccessors(Operation *op, 964 unsigned numSuccessors) { 965 if (op->getNumSuccessors() < numSuccessors) { 966 return op->emitOpError("requires at least ") 967 << numSuccessors << " successors but found " 968 << op->getNumSuccessors(); 969 } 970 return verifyTerminatorSuccessors(op); 971 } 972 973 LogicalResult OpTrait::impl::verifyResultsAreBoolLike(Operation *op) { 974 for (auto resultType : op->getResultTypes()) { 975 auto elementType = getTensorOrVectorElementType(resultType); 976 bool isBoolType = elementType.isInteger(1); 977 if (!isBoolType) 978 return op->emitOpError() << "requires a bool result type"; 979 } 980 981 return success(); 982 } 983 984 LogicalResult OpTrait::impl::verifyResultsAreFloatLike(Operation *op) { 985 for (auto resultType : op->getResultTypes()) 986 if (!getTensorOrVectorElementType(resultType).isa<FloatType>()) 987 return op->emitOpError() << "requires a floating point type"; 988 989 return success(); 990 } 991 992 LogicalResult 993 OpTrait::impl::verifyResultsAreSignlessIntegerLike(Operation *op) { 994 for (auto resultType : op->getResultTypes()) 995 if (!getTensorOrVectorElementType(resultType).isSignlessIntOrIndex()) 996 return op->emitOpError() << "requires an integer or index type"; 997 return success(); 998 } 999 1000 static LogicalResult verifyValueSizeAttr(Operation *op, StringRef attrName, 1001 bool isOperand) { 1002 auto sizeAttr = op->getAttrOfType<DenseIntElementsAttr>(attrName); 1003 if (!sizeAttr) 1004 return op->emitOpError("requires 1D vector attribute '") << attrName << "'"; 1005 1006 auto sizeAttrType = sizeAttr.getType().dyn_cast<VectorType>(); 1007 if (!sizeAttrType || sizeAttrType.getRank() != 1 || 1008 !sizeAttrType.getElementType().isInteger(32)) 1009 return op->emitOpError("requires 1D vector of i32 attribute '") 1010 << attrName << "'"; 1011 1012 if (llvm::any_of(sizeAttr.getIntValues(), [](const APInt &element) { 1013 return !element.isNonNegative(); 1014 })) 1015 return op->emitOpError("'") 1016 << attrName << "' attribute cannot have negative elements"; 1017 1018 size_t totalCount = std::accumulate( 1019 sizeAttr.begin(), sizeAttr.end(), 0, 1020 [](unsigned all, APInt one) { return all + one.getZExtValue(); }); 1021 1022 if (isOperand && totalCount != op->getNumOperands()) 1023 return op->emitOpError("operand count (") 1024 << op->getNumOperands() << ") does not match with the total size (" 1025 << totalCount << ") specified in attribute '" << attrName << "'"; 1026 else if (!isOperand && totalCount != op->getNumResults()) 1027 return op->emitOpError("result count (") 1028 << op->getNumResults() << ") does not match with the total size (" 1029 << totalCount << ") specified in attribute '" << attrName << "'"; 1030 return success(); 1031 } 1032 1033 LogicalResult OpTrait::impl::verifyOperandSizeAttr(Operation *op, 1034 StringRef attrName) { 1035 return verifyValueSizeAttr(op, attrName, /*isOperand=*/true); 1036 } 1037 1038 LogicalResult OpTrait::impl::verifyResultSizeAttr(Operation *op, 1039 StringRef attrName) { 1040 return verifyValueSizeAttr(op, attrName, /*isOperand=*/false); 1041 } 1042 1043 LogicalResult OpTrait::impl::verifyNoRegionArguments(Operation *op) { 1044 for (Region ®ion : op->getRegions()) { 1045 if (region.empty()) 1046 continue; 1047 1048 if (region.getNumArguments() != 0) { 1049 if (op->getNumRegions() > 1) 1050 return op->emitOpError("region #") 1051 << region.getRegionNumber() << " should have no arguments"; 1052 else 1053 return op->emitOpError("region should have no arguments"); 1054 } 1055 } 1056 return success(); 1057 } 1058 1059 LogicalResult OpTrait::impl::verifyElementwise(Operation *op) { 1060 auto isMappableType = [](Type type) { 1061 return type.isa<VectorType, TensorType>(); 1062 }; 1063 auto resultMappableTypes = llvm::to_vector<1>( 1064 llvm::make_filter_range(op->getResultTypes(), isMappableType)); 1065 auto operandMappableTypes = llvm::to_vector<2>( 1066 llvm::make_filter_range(op->getOperandTypes(), isMappableType)); 1067 1068 // If the op only has scalar operand/result types, then we have nothing to 1069 // check. 1070 if (resultMappableTypes.empty() && operandMappableTypes.empty()) 1071 return success(); 1072 1073 if (!resultMappableTypes.empty() && operandMappableTypes.empty()) 1074 return op->emitOpError("if a result is non-scalar, then at least one " 1075 "operand must be non-scalar"); 1076 1077 assert(!operandMappableTypes.empty()); 1078 1079 if (resultMappableTypes.empty()) 1080 return op->emitOpError("if an operand is non-scalar, then there must be at " 1081 "least one non-scalar result"); 1082 1083 if (resultMappableTypes.size() != op->getNumResults()) 1084 return op->emitOpError( 1085 "if an operand is non-scalar, then all results must be non-scalar"); 1086 1087 SmallVector<Type, 4> types = llvm::to_vector<2>( 1088 llvm::concat<Type>(operandMappableTypes, resultMappableTypes)); 1089 TypeID expectedBaseTy = types.front().getTypeID(); 1090 if (!llvm::all_of(types, 1091 [&](Type t) { return t.getTypeID() == expectedBaseTy; }) || 1092 failed(verifyCompatibleShapes(types))) { 1093 return op->emitOpError() << "all non-scalar operands/results must have the " 1094 "same shape and base type"; 1095 } 1096 1097 return success(); 1098 } 1099 1100 /// Check for any values used by operations regions attached to the 1101 /// specified "IsIsolatedFromAbove" operation defined outside of it. 1102 LogicalResult OpTrait::impl::verifyIsIsolatedFromAbove(Operation *isolatedOp) { 1103 assert(isolatedOp->hasTrait<OpTrait::IsIsolatedFromAbove>() && 1104 "Intended to check IsolatedFromAbove ops"); 1105 1106 // List of regions to analyze. Each region is processed independently, with 1107 // respect to the common `limit` region, so we can look at them in any order. 1108 // Therefore, use a simple vector and push/pop back the current region. 1109 SmallVector<Region *, 8> pendingRegions; 1110 for (auto ®ion : isolatedOp->getRegions()) { 1111 pendingRegions.push_back(®ion); 1112 1113 // Traverse all operations in the region. 1114 while (!pendingRegions.empty()) { 1115 for (Operation &op : pendingRegions.pop_back_val()->getOps()) { 1116 for (Value operand : op.getOperands()) { 1117 // operand should be non-null here if the IR is well-formed. But 1118 // we don't assert here as this function is called from the verifier 1119 // and so could be called on invalid IR. 1120 if (!operand) 1121 return op.emitOpError("operation's operand is null"); 1122 1123 // Check that any value that is used by an operation is defined in the 1124 // same region as either an operation result. 1125 auto *operandRegion = operand.getParentRegion(); 1126 if (!region.isAncestor(operandRegion)) { 1127 return op.emitOpError("using value defined outside the region") 1128 .attachNote(isolatedOp->getLoc()) 1129 << "required by region isolation constraints"; 1130 } 1131 } 1132 1133 // Schedule any regions in the operation for further checking. Don't 1134 // recurse into other IsolatedFromAbove ops, because they will check 1135 // themselves. 1136 if (op.getNumRegions() && 1137 !op.hasTrait<OpTrait::IsIsolatedFromAbove>()) { 1138 for (Region &subRegion : op.getRegions()) 1139 pendingRegions.push_back(&subRegion); 1140 } 1141 } 1142 } 1143 } 1144 1145 return success(); 1146 } 1147 1148 bool OpTrait::hasElementwiseMappableTraits(Operation *op) { 1149 return op->hasTrait<Elementwise>() && op->hasTrait<Scalarizable>() && 1150 op->hasTrait<Vectorizable>() && op->hasTrait<Tensorizable>(); 1151 } 1152 1153 //===----------------------------------------------------------------------===// 1154 // BinaryOp implementation 1155 //===----------------------------------------------------------------------===// 1156 1157 // These functions are out-of-line implementations of the methods in BinaryOp, 1158 // which avoids them being template instantiated/duplicated. 1159 1160 void impl::buildBinaryOp(OpBuilder &builder, OperationState &result, Value lhs, 1161 Value rhs) { 1162 assert(lhs.getType() == rhs.getType()); 1163 result.addOperands({lhs, rhs}); 1164 result.types.push_back(lhs.getType()); 1165 } 1166 1167 ParseResult impl::parseOneResultSameOperandTypeOp(OpAsmParser &parser, 1168 OperationState &result) { 1169 SmallVector<OpAsmParser::OperandType, 2> ops; 1170 Type type; 1171 return failure(parser.parseOperandList(ops) || 1172 parser.parseOptionalAttrDict(result.attributes) || 1173 parser.parseColonType(type) || 1174 parser.resolveOperands(ops, type, result.operands) || 1175 parser.addTypeToList(type, result.types)); 1176 } 1177 1178 void impl::printOneResultOp(Operation *op, OpAsmPrinter &p) { 1179 assert(op->getNumResults() == 1 && "op should have one result"); 1180 1181 // If not all the operand and result types are the same, just use the 1182 // generic assembly form to avoid omitting information in printing. 1183 auto resultType = op->getResult(0).getType(); 1184 if (llvm::any_of(op->getOperandTypes(), 1185 [&](Type type) { return type != resultType; })) { 1186 p.printGenericOp(op); 1187 return; 1188 } 1189 1190 p << op->getName() << ' '; 1191 p.printOperands(op->getOperands()); 1192 p.printOptionalAttrDict(op->getAttrs()); 1193 // Now we can output only one type for all operands and the result. 1194 p << " : " << resultType; 1195 } 1196 1197 //===----------------------------------------------------------------------===// 1198 // CastOp implementation 1199 //===----------------------------------------------------------------------===// 1200 1201 /// Attempt to fold the given cast operation. 1202 LogicalResult 1203 impl::foldCastInterfaceOp(Operation *op, ArrayRef<Attribute> attrOperands, 1204 SmallVectorImpl<OpFoldResult> &foldResults) { 1205 OperandRange operands = op->getOperands(); 1206 if (operands.empty()) 1207 return failure(); 1208 ResultRange results = op->getResults(); 1209 1210 // Check for the case where the input and output types match 1-1. 1211 if (operands.getTypes() == results.getTypes()) { 1212 foldResults.append(operands.begin(), operands.end()); 1213 return success(); 1214 } 1215 1216 return failure(); 1217 } 1218 1219 /// Attempt to verify the given cast operation. 1220 LogicalResult impl::verifyCastInterfaceOp( 1221 Operation *op, function_ref<bool(TypeRange, TypeRange)> areCastCompatible) { 1222 auto resultTypes = op->getResultTypes(); 1223 if (llvm::empty(resultTypes)) 1224 return op->emitOpError() 1225 << "expected at least one result for cast operation"; 1226 1227 auto operandTypes = op->getOperandTypes(); 1228 if (!areCastCompatible(operandTypes, resultTypes)) { 1229 InFlightDiagnostic diag = op->emitOpError("operand type"); 1230 if (llvm::empty(operandTypes)) 1231 diag << "s []"; 1232 else if (llvm::size(operandTypes) == 1) 1233 diag << " " << *operandTypes.begin(); 1234 else 1235 diag << "s " << operandTypes; 1236 return diag << " and result type" << (resultTypes.size() == 1 ? " " : "s ") 1237 << resultTypes << " are cast incompatible"; 1238 } 1239 1240 return success(); 1241 } 1242 1243 void impl::buildCastOp(OpBuilder &builder, OperationState &result, Value source, 1244 Type destType) { 1245 result.addOperands(source); 1246 result.addTypes(destType); 1247 } 1248 1249 ParseResult impl::parseCastOp(OpAsmParser &parser, OperationState &result) { 1250 OpAsmParser::OperandType srcInfo; 1251 Type srcType, dstType; 1252 return failure(parser.parseOperand(srcInfo) || 1253 parser.parseOptionalAttrDict(result.attributes) || 1254 parser.parseColonType(srcType) || 1255 parser.resolveOperand(srcInfo, srcType, result.operands) || 1256 parser.parseKeywordType("to", dstType) || 1257 parser.addTypeToList(dstType, result.types)); 1258 } 1259 1260 void impl::printCastOp(Operation *op, OpAsmPrinter &p) { 1261 p << op->getName() << ' ' << op->getOperand(0); 1262 p.printOptionalAttrDict(op->getAttrs()); 1263 p << " : " << op->getOperand(0).getType() << " to " 1264 << op->getResult(0).getType(); 1265 } 1266 1267 Value impl::foldCastOp(Operation *op) { 1268 // Identity cast 1269 if (op->getOperand(0).getType() == op->getResult(0).getType()) 1270 return op->getOperand(0); 1271 return nullptr; 1272 } 1273 1274 LogicalResult 1275 impl::verifyCastOp(Operation *op, 1276 function_ref<bool(Type, Type)> areCastCompatible) { 1277 auto opType = op->getOperand(0).getType(); 1278 auto resType = op->getResult(0).getType(); 1279 if (!areCastCompatible(opType, resType)) 1280 return op->emitError("operand type ") 1281 << opType << " and result type " << resType 1282 << " are cast incompatible"; 1283 1284 return success(); 1285 } 1286 1287 //===----------------------------------------------------------------------===// 1288 // Misc. utils 1289 //===----------------------------------------------------------------------===// 1290 1291 /// Insert an operation, generated by `buildTerminatorOp`, at the end of the 1292 /// region's only block if it does not have a terminator already. If the region 1293 /// is empty, insert a new block first. `buildTerminatorOp` should return the 1294 /// terminator operation to insert. 1295 void impl::ensureRegionTerminator( 1296 Region ®ion, OpBuilder &builder, Location loc, 1297 function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) { 1298 OpBuilder::InsertionGuard guard(builder); 1299 if (region.empty()) 1300 builder.createBlock(®ion); 1301 1302 Block &block = region.back(); 1303 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>()) 1304 return; 1305 1306 builder.setInsertionPointToEnd(&block); 1307 builder.insert(buildTerminatorOp(builder, loc)); 1308 } 1309 1310 /// Create a simple OpBuilder and forward to the OpBuilder version of this 1311 /// function. 1312 void impl::ensureRegionTerminator( 1313 Region ®ion, Builder &builder, Location loc, 1314 function_ref<Operation *(OpBuilder &, Location)> buildTerminatorOp) { 1315 OpBuilder opBuilder(builder.getContext()); 1316 ensureRegionTerminator(region, opBuilder, loc, buildTerminatorOp); 1317 } 1318 1319 //===----------------------------------------------------------------------===// 1320 // UseIterator 1321 //===----------------------------------------------------------------------===// 1322 1323 Operation::UseIterator::UseIterator(Operation *op, bool end) 1324 : op(op), res(end ? op->result_end() : op->result_begin()) { 1325 // Only initialize current use if there are results/can be uses. 1326 if (op->getNumResults()) 1327 skipOverResultsWithNoUsers(); 1328 } 1329 1330 Operation::UseIterator &Operation::UseIterator::operator++() { 1331 // We increment over uses, if we reach the last use then move to next 1332 // result. 1333 if (use != (*res).use_end()) 1334 ++use; 1335 if (use == (*res).use_end()) { 1336 ++res; 1337 skipOverResultsWithNoUsers(); 1338 } 1339 return *this; 1340 } 1341 1342 void Operation::UseIterator::skipOverResultsWithNoUsers() { 1343 while (res != op->result_end() && (*res).use_empty()) 1344 ++res; 1345 1346 // If we are at the last result, then set use to first use of 1347 // first result (sentinel value used for end). 1348 if (res == op->result_end()) 1349 use = {}; 1350 else 1351 use = (*res).use_begin(); 1352 } 1353