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