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