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