1 //===- SymbolTable.cpp - MLIR Symbol Table Class --------------------------===// 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/SymbolTable.h" 10 #include "mlir/IR/Builders.h" 11 #include "mlir/IR/OpImplementation.h" 12 #include "llvm/ADT/SetVector.h" 13 #include "llvm/ADT/SmallPtrSet.h" 14 #include "llvm/ADT/SmallString.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include <optional> 17 18 using namespace mlir; 19 20 /// Return true if the given operation is unknown and may potentially define a 21 /// symbol table. 22 static bool isPotentiallyUnknownSymbolTable(Operation *op) { 23 return op->getNumRegions() == 1 && !op->getDialect(); 24 } 25 26 /// Returns the string name of the given symbol, or null if this is not a 27 /// symbol. 28 static StringAttr getNameIfSymbol(Operation *op) { 29 return op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()); 30 } 31 static StringAttr getNameIfSymbol(Operation *op, StringAttr symbolAttrNameId) { 32 return op->getAttrOfType<StringAttr>(symbolAttrNameId); 33 } 34 35 /// Computes the nested symbol reference attribute for the symbol 'symbolName' 36 /// that are usable within the symbol table operations from 'symbol' as far up 37 /// to the given operation 'within', where 'within' is an ancestor of 'symbol'. 38 /// Returns success if all references up to 'within' could be computed. 39 static LogicalResult 40 collectValidReferencesFor(Operation *symbol, StringAttr symbolName, 41 Operation *within, 42 SmallVectorImpl<SymbolRefAttr> &results) { 43 assert(within->isAncestor(symbol) && "expected 'within' to be an ancestor"); 44 MLIRContext *ctx = symbol->getContext(); 45 46 auto leafRef = FlatSymbolRefAttr::get(symbolName); 47 results.push_back(leafRef); 48 49 // Early exit for when 'within' is the parent of 'symbol'. 50 Operation *symbolTableOp = symbol->getParentOp(); 51 if (within == symbolTableOp) 52 return success(); 53 54 // Collect references until 'symbolTableOp' reaches 'within'. 55 SmallVector<FlatSymbolRefAttr, 1> nestedRefs(1, leafRef); 56 StringAttr symbolNameId = 57 StringAttr::get(ctx, SymbolTable::getSymbolAttrName()); 58 do { 59 // Each parent of 'symbol' should define a symbol table. 60 if (!symbolTableOp->hasTrait<OpTrait::SymbolTable>()) 61 return failure(); 62 // Each parent of 'symbol' should also be a symbol. 63 StringAttr symbolTableName = getNameIfSymbol(symbolTableOp, symbolNameId); 64 if (!symbolTableName) 65 return failure(); 66 results.push_back(SymbolRefAttr::get(symbolTableName, nestedRefs)); 67 68 symbolTableOp = symbolTableOp->getParentOp(); 69 if (symbolTableOp == within) 70 break; 71 nestedRefs.insert(nestedRefs.begin(), 72 FlatSymbolRefAttr::get(symbolTableName)); 73 } while (true); 74 return success(); 75 } 76 77 /// Walk all of the operations within the given set of regions, without 78 /// traversing into any nested symbol tables. Stops walking if the result of the 79 /// callback is anything other than `WalkResult::advance`. 80 static Optional<WalkResult> 81 walkSymbolTable(MutableArrayRef<Region> regions, 82 function_ref<Optional<WalkResult>(Operation *)> callback) { 83 SmallVector<Region *, 1> worklist(llvm::make_pointer_range(regions)); 84 while (!worklist.empty()) { 85 for (Operation &op : worklist.pop_back_val()->getOps()) { 86 Optional<WalkResult> result = callback(&op); 87 if (result != WalkResult::advance()) 88 return result; 89 90 // If this op defines a new symbol table scope, we can't traverse. Any 91 // symbol references nested within 'op' are different semantically. 92 if (!op.hasTrait<OpTrait::SymbolTable>()) { 93 for (Region ®ion : op.getRegions()) 94 worklist.push_back(®ion); 95 } 96 } 97 } 98 return WalkResult::advance(); 99 } 100 101 /// Walk all of the operations nested under, and including, the given operation, 102 /// without traversing into any nested symbol tables. Stops walking if the 103 /// result of the callback is anything other than `WalkResult::advance`. 104 static Optional<WalkResult> 105 walkSymbolTable(Operation *op, 106 function_ref<Optional<WalkResult>(Operation *)> callback) { 107 Optional<WalkResult> result = callback(op); 108 if (result != WalkResult::advance() || op->hasTrait<OpTrait::SymbolTable>()) 109 return result; 110 return walkSymbolTable(op->getRegions(), callback); 111 } 112 113 //===----------------------------------------------------------------------===// 114 // SymbolTable 115 //===----------------------------------------------------------------------===// 116 117 /// Build a symbol table with the symbols within the given operation. 118 SymbolTable::SymbolTable(Operation *symbolTableOp) 119 : symbolTableOp(symbolTableOp) { 120 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>() && 121 "expected operation to have SymbolTable trait"); 122 assert(symbolTableOp->getNumRegions() == 1 && 123 "expected operation to have a single region"); 124 assert(llvm::hasSingleElement(symbolTableOp->getRegion(0)) && 125 "expected operation to have a single block"); 126 127 StringAttr symbolNameId = StringAttr::get(symbolTableOp->getContext(), 128 SymbolTable::getSymbolAttrName()); 129 for (auto &op : symbolTableOp->getRegion(0).front()) { 130 StringAttr name = getNameIfSymbol(&op, symbolNameId); 131 if (!name) 132 continue; 133 134 auto inserted = symbolTable.insert({name, &op}); 135 (void)inserted; 136 assert(inserted.second && 137 "expected region to contain uniquely named symbol operations"); 138 } 139 } 140 141 /// Look up a symbol with the specified name, returning null if no such name 142 /// exists. Names never include the @ on them. 143 Operation *SymbolTable::lookup(StringRef name) const { 144 return lookup(StringAttr::get(symbolTableOp->getContext(), name)); 145 } 146 Operation *SymbolTable::lookup(StringAttr name) const { 147 return symbolTable.lookup(name); 148 } 149 150 void SymbolTable::remove(Operation *op) { 151 StringAttr name = getNameIfSymbol(op); 152 assert(name && "expected valid 'name' attribute"); 153 assert(op->getParentOp() == symbolTableOp && 154 "expected this operation to be inside of the operation with this " 155 "SymbolTable"); 156 157 auto it = symbolTable.find(name); 158 if (it != symbolTable.end() && it->second == op) 159 symbolTable.erase(it); 160 } 161 162 void SymbolTable::erase(Operation *symbol) { 163 remove(symbol); 164 symbol->erase(); 165 } 166 167 // TODO: Consider if this should be renamed to something like insertOrUpdate 168 /// Insert a new symbol into the table and associated operation if not already 169 /// there and rename it as necessary to avoid collisions. Return the name of 170 /// the symbol after insertion as attribute. 171 StringAttr SymbolTable::insert(Operation *symbol, Block::iterator insertPt) { 172 // The symbol cannot be the child of another op and must be the child of the 173 // symbolTableOp after this. 174 // 175 // TODO: consider if SymbolTable's constructor should behave the same. 176 if (!symbol->getParentOp()) { 177 auto &body = symbolTableOp->getRegion(0).front(); 178 if (insertPt == Block::iterator()) { 179 insertPt = Block::iterator(body.end()); 180 } else { 181 assert((insertPt == body.end() || 182 insertPt->getParentOp() == symbolTableOp) && 183 "expected insertPt to be in the associated module operation"); 184 } 185 // Insert before the terminator, if any. 186 if (insertPt == Block::iterator(body.end()) && !body.empty() && 187 std::prev(body.end())->hasTrait<OpTrait::IsTerminator>()) 188 insertPt = std::prev(body.end()); 189 190 body.getOperations().insert(insertPt, symbol); 191 } 192 assert(symbol->getParentOp() == symbolTableOp && 193 "symbol is already inserted in another op"); 194 195 // Add this symbol to the symbol table, uniquing the name if a conflict is 196 // detected. 197 StringAttr name = getSymbolName(symbol); 198 if (symbolTable.insert({name, symbol}).second) 199 return name; 200 // If the symbol was already in the table, also return. 201 if (symbolTable.lookup(name) == symbol) 202 return name; 203 // If a conflict was detected, then the symbol will not have been added to 204 // the symbol table. Try suffixes until we get to a unique name that works. 205 SmallString<128> nameBuffer(name.getValue()); 206 unsigned originalLength = nameBuffer.size(); 207 208 MLIRContext *context = symbol->getContext(); 209 210 // Iteratively try suffixes until we find one that isn't used. 211 do { 212 nameBuffer.resize(originalLength); 213 nameBuffer += '_'; 214 nameBuffer += std::to_string(uniquingCounter++); 215 } while (!symbolTable.insert({StringAttr::get(context, nameBuffer), symbol}) 216 .second); 217 setSymbolName(symbol, nameBuffer); 218 return getSymbolName(symbol); 219 } 220 221 /// Returns the name of the given symbol operation. 222 StringAttr SymbolTable::getSymbolName(Operation *symbol) { 223 StringAttr name = getNameIfSymbol(symbol); 224 assert(name && "expected valid symbol name"); 225 return name; 226 } 227 228 /// Sets the name of the given symbol operation. 229 void SymbolTable::setSymbolName(Operation *symbol, StringAttr name) { 230 symbol->setAttr(getSymbolAttrName(), name); 231 } 232 233 /// Returns the visibility of the given symbol operation. 234 SymbolTable::Visibility SymbolTable::getSymbolVisibility(Operation *symbol) { 235 // If the attribute doesn't exist, assume public. 236 StringAttr vis = symbol->getAttrOfType<StringAttr>(getVisibilityAttrName()); 237 if (!vis) 238 return Visibility::Public; 239 240 // Otherwise, switch on the string value. 241 return StringSwitch<Visibility>(vis.getValue()) 242 .Case("private", Visibility::Private) 243 .Case("nested", Visibility::Nested) 244 .Case("public", Visibility::Public); 245 } 246 /// Sets the visibility of the given symbol operation. 247 void SymbolTable::setSymbolVisibility(Operation *symbol, Visibility vis) { 248 MLIRContext *ctx = symbol->getContext(); 249 250 // If the visibility is public, just drop the attribute as this is the 251 // default. 252 if (vis == Visibility::Public) { 253 symbol->removeAttr(StringAttr::get(ctx, getVisibilityAttrName())); 254 return; 255 } 256 257 // Otherwise, update the attribute. 258 assert((vis == Visibility::Private || vis == Visibility::Nested) && 259 "unknown symbol visibility kind"); 260 261 StringRef visName = vis == Visibility::Private ? "private" : "nested"; 262 symbol->setAttr(getVisibilityAttrName(), StringAttr::get(ctx, visName)); 263 } 264 265 /// Returns the nearest symbol table from a given operation `from`. Returns 266 /// nullptr if no valid parent symbol table could be found. 267 Operation *SymbolTable::getNearestSymbolTable(Operation *from) { 268 assert(from && "expected valid operation"); 269 if (isPotentiallyUnknownSymbolTable(from)) 270 return nullptr; 271 272 while (!from->hasTrait<OpTrait::SymbolTable>()) { 273 from = from->getParentOp(); 274 275 // Check that this is a valid op and isn't an unknown symbol table. 276 if (!from || isPotentiallyUnknownSymbolTable(from)) 277 return nullptr; 278 } 279 return from; 280 } 281 282 /// Walks all symbol table operations nested within, and including, `op`. For 283 /// each symbol table operation, the provided callback is invoked with the op 284 /// and a boolean signifying if the symbols within that symbol table can be 285 /// treated as if all uses are visible. `allSymUsesVisible` identifies whether 286 /// all of the symbol uses of symbols within `op` are visible. 287 void SymbolTable::walkSymbolTables( 288 Operation *op, bool allSymUsesVisible, 289 function_ref<void(Operation *, bool)> callback) { 290 bool isSymbolTable = op->hasTrait<OpTrait::SymbolTable>(); 291 if (isSymbolTable) { 292 SymbolOpInterface symbol = dyn_cast<SymbolOpInterface>(op); 293 allSymUsesVisible |= !symbol || symbol.isPrivate(); 294 } else { 295 // Otherwise if 'op' is not a symbol table, any nested symbols are 296 // guaranteed to be hidden. 297 allSymUsesVisible = true; 298 } 299 300 for (Region ®ion : op->getRegions()) 301 for (Block &block : region) 302 for (Operation &nestedOp : block) 303 walkSymbolTables(&nestedOp, allSymUsesVisible, callback); 304 305 // If 'op' had the symbol table trait, visit it after any nested symbol 306 // tables. 307 if (isSymbolTable) 308 callback(op, allSymUsesVisible); 309 } 310 311 /// Returns the operation registered with the given symbol name with the 312 /// regions of 'symbolTableOp'. 'symbolTableOp' is required to be an operation 313 /// with the 'OpTrait::SymbolTable' trait. Returns nullptr if no valid symbol 314 /// was found. 315 Operation *SymbolTable::lookupSymbolIn(Operation *symbolTableOp, 316 StringAttr symbol) { 317 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>()); 318 Region ®ion = symbolTableOp->getRegion(0); 319 if (region.empty()) 320 return nullptr; 321 322 // Look for a symbol with the given name. 323 StringAttr symbolNameId = StringAttr::get(symbolTableOp->getContext(), 324 SymbolTable::getSymbolAttrName()); 325 for (auto &op : region.front()) 326 if (getNameIfSymbol(&op, symbolNameId) == symbol) 327 return &op; 328 return nullptr; 329 } 330 Operation *SymbolTable::lookupSymbolIn(Operation *symbolTableOp, 331 SymbolRefAttr symbol) { 332 SmallVector<Operation *, 4> resolvedSymbols; 333 if (failed(lookupSymbolIn(symbolTableOp, symbol, resolvedSymbols))) 334 return nullptr; 335 return resolvedSymbols.back(); 336 } 337 338 /// Internal implementation of `lookupSymbolIn` that allows for specialized 339 /// implementations of the lookup function. 340 static LogicalResult lookupSymbolInImpl( 341 Operation *symbolTableOp, SymbolRefAttr symbol, 342 SmallVectorImpl<Operation *> &symbols, 343 function_ref<Operation *(Operation *, StringAttr)> lookupSymbolFn) { 344 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>()); 345 346 // Lookup the root reference for this symbol. 347 symbolTableOp = lookupSymbolFn(symbolTableOp, symbol.getRootReference()); 348 if (!symbolTableOp) 349 return failure(); 350 symbols.push_back(symbolTableOp); 351 352 // If there are no nested references, just return the root symbol directly. 353 ArrayRef<FlatSymbolRefAttr> nestedRefs = symbol.getNestedReferences(); 354 if (nestedRefs.empty()) 355 return success(); 356 357 // Verify that the root is also a symbol table. 358 if (!symbolTableOp->hasTrait<OpTrait::SymbolTable>()) 359 return failure(); 360 361 // Otherwise, lookup each of the nested non-leaf references and ensure that 362 // each corresponds to a valid symbol table. 363 for (FlatSymbolRefAttr ref : nestedRefs.drop_back()) { 364 symbolTableOp = lookupSymbolFn(symbolTableOp, ref.getAttr()); 365 if (!symbolTableOp || !symbolTableOp->hasTrait<OpTrait::SymbolTable>()) 366 return failure(); 367 symbols.push_back(symbolTableOp); 368 } 369 symbols.push_back(lookupSymbolFn(symbolTableOp, symbol.getLeafReference())); 370 return success(symbols.back()); 371 } 372 373 LogicalResult 374 SymbolTable::lookupSymbolIn(Operation *symbolTableOp, SymbolRefAttr symbol, 375 SmallVectorImpl<Operation *> &symbols) { 376 auto lookupFn = [](Operation *symbolTableOp, StringAttr symbol) { 377 return lookupSymbolIn(symbolTableOp, symbol); 378 }; 379 return lookupSymbolInImpl(symbolTableOp, symbol, symbols, lookupFn); 380 } 381 382 /// Returns the operation registered with the given symbol name within the 383 /// closes parent operation with the 'OpTrait::SymbolTable' trait. Returns 384 /// nullptr if no valid symbol was found. 385 Operation *SymbolTable::lookupNearestSymbolFrom(Operation *from, 386 StringAttr symbol) { 387 Operation *symbolTableOp = getNearestSymbolTable(from); 388 return symbolTableOp ? lookupSymbolIn(symbolTableOp, symbol) : nullptr; 389 } 390 Operation *SymbolTable::lookupNearestSymbolFrom(Operation *from, 391 SymbolRefAttr symbol) { 392 Operation *symbolTableOp = getNearestSymbolTable(from); 393 return symbolTableOp ? lookupSymbolIn(symbolTableOp, symbol) : nullptr; 394 } 395 396 raw_ostream &mlir::operator<<(raw_ostream &os, 397 SymbolTable::Visibility visibility) { 398 switch (visibility) { 399 case SymbolTable::Visibility::Public: 400 return os << "public"; 401 case SymbolTable::Visibility::Private: 402 return os << "private"; 403 case SymbolTable::Visibility::Nested: 404 return os << "nested"; 405 } 406 llvm_unreachable("Unexpected visibility"); 407 } 408 409 //===----------------------------------------------------------------------===// 410 // SymbolTable Trait Types 411 //===----------------------------------------------------------------------===// 412 413 LogicalResult detail::verifySymbolTable(Operation *op) { 414 if (op->getNumRegions() != 1) 415 return op->emitOpError() 416 << "Operations with a 'SymbolTable' must have exactly one region"; 417 if (!llvm::hasSingleElement(op->getRegion(0))) 418 return op->emitOpError() 419 << "Operations with a 'SymbolTable' must have exactly one block"; 420 421 // Check that all symbols are uniquely named within child regions. 422 DenseMap<Attribute, Location> nameToOrigLoc; 423 for (auto &block : op->getRegion(0)) { 424 for (auto &op : block) { 425 // Check for a symbol name attribute. 426 auto nameAttr = 427 op.getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()); 428 if (!nameAttr) 429 continue; 430 431 // Try to insert this symbol into the table. 432 auto it = nameToOrigLoc.try_emplace(nameAttr, op.getLoc()); 433 if (!it.second) 434 return op.emitError() 435 .append("redefinition of symbol named '", nameAttr.getValue(), "'") 436 .attachNote(it.first->second) 437 .append("see existing symbol definition here"); 438 } 439 } 440 441 // Verify any nested symbol user operations. 442 SymbolTableCollection symbolTable; 443 auto verifySymbolUserFn = [&](Operation *op) -> Optional<WalkResult> { 444 if (SymbolUserOpInterface user = dyn_cast<SymbolUserOpInterface>(op)) 445 return WalkResult(user.verifySymbolUses(symbolTable)); 446 return WalkResult::advance(); 447 }; 448 449 Optional<WalkResult> result = 450 walkSymbolTable(op->getRegions(), verifySymbolUserFn); 451 return success(result && !result->wasInterrupted()); 452 } 453 454 LogicalResult detail::verifySymbol(Operation *op) { 455 // Verify the name attribute. 456 if (!op->getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName())) 457 return op->emitOpError() << "requires string attribute '" 458 << mlir::SymbolTable::getSymbolAttrName() << "'"; 459 460 // Verify the visibility attribute. 461 if (Attribute vis = op->getAttr(mlir::SymbolTable::getVisibilityAttrName())) { 462 StringAttr visStrAttr = vis.dyn_cast<StringAttr>(); 463 if (!visStrAttr) 464 return op->emitOpError() << "requires visibility attribute '" 465 << mlir::SymbolTable::getVisibilityAttrName() 466 << "' to be a string attribute, but got " << vis; 467 468 if (!llvm::is_contained(ArrayRef<StringRef>{"public", "private", "nested"}, 469 visStrAttr.getValue())) 470 return op->emitOpError() 471 << "visibility expected to be one of [\"public\", \"private\", " 472 "\"nested\"], but got " 473 << visStrAttr; 474 } 475 return success(); 476 } 477 478 //===----------------------------------------------------------------------===// 479 // Symbol Use Lists 480 //===----------------------------------------------------------------------===// 481 482 /// Walk all of the symbol references within the given operation, invoking the 483 /// provided callback for each found use. The callbacks takes the use of the 484 /// symbol. 485 static WalkResult 486 walkSymbolRefs(Operation *op, 487 function_ref<WalkResult(SymbolTable::SymbolUse)> callback) { 488 // Check to see if the operation has any attributes. 489 DictionaryAttr attrDict = op->getAttrDictionary(); 490 if (attrDict.empty()) 491 return WalkResult::advance(); 492 493 // A worklist of a container attribute and the current index into the held 494 // attribute list. 495 struct WorklistItem { 496 SubElementAttrInterface container; 497 SmallVector<Attribute> immediateSubElements; 498 499 explicit WorklistItem(SubElementAttrInterface container) { 500 SmallVector<Attribute> subElements; 501 container.walkImmediateSubElements( 502 [&](Attribute attr) { subElements.push_back(attr); }, [](Type) {}); 503 immediateSubElements = std::move(subElements); 504 } 505 }; 506 507 SmallVector<WorklistItem, 1> attrWorklist(1, WorklistItem(attrDict)); 508 SmallVector<int, 1> curAccessChain(1, /*Value=*/-1); 509 510 // Process the symbol references within the given nested attribute range. 511 auto processAttrs = [&](int &index, 512 WorklistItem &worklistItem) -> WalkResult { 513 for (Attribute attr : 514 llvm::drop_begin(worklistItem.immediateSubElements, index)) { 515 // Invoke the provided callback if we find a symbol use and check for a 516 // requested interrupt. 517 if (auto symbolRef = attr.dyn_cast<SymbolRefAttr>()) { 518 if (callback({op, symbolRef}).wasInterrupted()) 519 return WalkResult::interrupt(); 520 521 /// Check for a nested container attribute, these will also need to be 522 /// walked. 523 } else if (auto interface = attr.dyn_cast<SubElementAttrInterface>()) { 524 attrWorklist.emplace_back(interface); 525 curAccessChain.push_back(-1); 526 return WalkResult::advance(); 527 } 528 // Make sure to keep the index counter in sync. 529 ++index; 530 } 531 532 // Pop this container attribute from the worklist. 533 attrWorklist.pop_back(); 534 curAccessChain.pop_back(); 535 return WalkResult::advance(); 536 }; 537 538 WalkResult result = WalkResult::advance(); 539 do { 540 WorklistItem &item = attrWorklist.back(); 541 int &index = curAccessChain.back(); 542 ++index; 543 544 // Process the given attribute, which is guaranteed to be a container. 545 result = processAttrs(index, item); 546 } while (!attrWorklist.empty() && !result.wasInterrupted()); 547 return result; 548 } 549 550 /// Walk all of the uses, for any symbol, that are nested within the given 551 /// regions, invoking the provided callback for each. This does not traverse 552 /// into any nested symbol tables. 553 static Optional<WalkResult> 554 walkSymbolUses(MutableArrayRef<Region> regions, 555 function_ref<WalkResult(SymbolTable::SymbolUse)> callback) { 556 return walkSymbolTable(regions, [&](Operation *op) -> Optional<WalkResult> { 557 // Check that this isn't a potentially unknown symbol table. 558 if (isPotentiallyUnknownSymbolTable(op)) 559 return std::nullopt; 560 561 return walkSymbolRefs(op, callback); 562 }); 563 } 564 /// Walk all of the uses, for any symbol, that are nested within the given 565 /// operation 'from', invoking the provided callback for each. This does not 566 /// traverse into any nested symbol tables. 567 static Optional<WalkResult> 568 walkSymbolUses(Operation *from, 569 function_ref<WalkResult(SymbolTable::SymbolUse)> callback) { 570 // If this operation has regions, and it, as well as its dialect, isn't 571 // registered then conservatively fail. The operation may define a 572 // symbol table, so we can't opaquely know if we should traverse to find 573 // nested uses. 574 if (isPotentiallyUnknownSymbolTable(from)) 575 return std::nullopt; 576 577 // Walk the uses on this operation. 578 if (walkSymbolRefs(from, callback).wasInterrupted()) 579 return WalkResult::interrupt(); 580 581 // Only recurse if this operation is not a symbol table. A symbol table 582 // defines a new scope, so we can't walk the attributes from within the symbol 583 // table op. 584 if (!from->hasTrait<OpTrait::SymbolTable>()) 585 return walkSymbolUses(from->getRegions(), callback); 586 return WalkResult::advance(); 587 } 588 589 namespace { 590 /// This class represents a single symbol scope. A symbol scope represents the 591 /// set of operations nested within a symbol table that may reference symbols 592 /// within that table. A symbol scope does not contain the symbol table 593 /// operation itself, just its contained operations. A scope ends at leaf 594 /// operations or another symbol table operation. 595 struct SymbolScope { 596 /// Walk the symbol uses within this scope, invoking the given callback. 597 /// This variant is used when the callback type matches that expected by 598 /// 'walkSymbolUses'. 599 template <typename CallbackT, 600 std::enable_if_t<!std::is_same< 601 typename llvm::function_traits<CallbackT>::result_t, 602 void>::value> * = nullptr> 603 Optional<WalkResult> walk(CallbackT cback) { 604 if (Region *region = limit.dyn_cast<Region *>()) 605 return walkSymbolUses(*region, cback); 606 return walkSymbolUses(limit.get<Operation *>(), cback); 607 } 608 /// This variant is used when the callback type matches a stripped down type: 609 /// void(SymbolTable::SymbolUse use) 610 template <typename CallbackT, 611 std::enable_if_t<std::is_same< 612 typename llvm::function_traits<CallbackT>::result_t, 613 void>::value> * = nullptr> 614 Optional<WalkResult> walk(CallbackT cback) { 615 return walk([=](SymbolTable::SymbolUse use) { 616 return cback(use), WalkResult::advance(); 617 }); 618 } 619 620 /// Walk all of the operations nested under the current scope without 621 /// traversing into any nested symbol tables. 622 template <typename CallbackT> 623 Optional<WalkResult> walkSymbolTable(CallbackT &&cback) { 624 if (Region *region = limit.dyn_cast<Region *>()) 625 return ::walkSymbolTable(*region, cback); 626 return ::walkSymbolTable(limit.get<Operation *>(), cback); 627 } 628 629 /// The representation of the symbol within this scope. 630 SymbolRefAttr symbol; 631 632 /// The IR unit representing this scope. 633 llvm::PointerUnion<Operation *, Region *> limit; 634 }; 635 } // namespace 636 637 /// Collect all of the symbol scopes from 'symbol' to (inclusive) 'limit'. 638 static SmallVector<SymbolScope, 2> collectSymbolScopes(Operation *symbol, 639 Operation *limit) { 640 StringAttr symName = SymbolTable::getSymbolName(symbol); 641 assert(!symbol->hasTrait<OpTrait::SymbolTable>() || symbol != limit); 642 643 // Compute the ancestors of 'limit'. 644 SetVector<Operation *, SmallVector<Operation *, 4>, 645 SmallPtrSet<Operation *, 4>> 646 limitAncestors; 647 Operation *limitAncestor = limit; 648 do { 649 // Check to see if 'symbol' is an ancestor of 'limit'. 650 if (limitAncestor == symbol) { 651 // Check that the nearest symbol table is 'symbol's parent. SymbolRefAttr 652 // doesn't support parent references. 653 if (SymbolTable::getNearestSymbolTable(limit->getParentOp()) == 654 symbol->getParentOp()) 655 return {{SymbolRefAttr::get(symName), limit}}; 656 return {}; 657 } 658 659 limitAncestors.insert(limitAncestor); 660 } while ((limitAncestor = limitAncestor->getParentOp())); 661 662 // Try to find the first ancestor of 'symbol' that is an ancestor of 'limit'. 663 Operation *commonAncestor = symbol->getParentOp(); 664 do { 665 if (limitAncestors.count(commonAncestor)) 666 break; 667 } while ((commonAncestor = commonAncestor->getParentOp())); 668 assert(commonAncestor && "'limit' and 'symbol' have no common ancestor"); 669 670 // Compute the set of valid nested references for 'symbol' as far up to the 671 // common ancestor as possible. 672 SmallVector<SymbolRefAttr, 2> references; 673 bool collectedAllReferences = succeeded( 674 collectValidReferencesFor(symbol, symName, commonAncestor, references)); 675 676 // Handle the case where the common ancestor is 'limit'. 677 if (commonAncestor == limit) { 678 SmallVector<SymbolScope, 2> scopes; 679 680 // Walk each of the ancestors of 'symbol', calling the compute function for 681 // each one. 682 Operation *limitIt = symbol->getParentOp(); 683 for (size_t i = 0, e = references.size(); i != e; 684 ++i, limitIt = limitIt->getParentOp()) { 685 assert(limitIt->hasTrait<OpTrait::SymbolTable>()); 686 scopes.push_back({references[i], &limitIt->getRegion(0)}); 687 } 688 return scopes; 689 } 690 691 // Otherwise, we just need the symbol reference for 'symbol' that will be 692 // used within 'limit'. This is the last reference in the list we computed 693 // above if we were able to collect all references. 694 if (!collectedAllReferences) 695 return {}; 696 return {{references.back(), limit}}; 697 } 698 static SmallVector<SymbolScope, 2> collectSymbolScopes(Operation *symbol, 699 Region *limit) { 700 auto scopes = collectSymbolScopes(symbol, limit->getParentOp()); 701 702 // If we collected some scopes to walk, make sure to constrain the one for 703 // limit to the specific region requested. 704 if (!scopes.empty()) 705 scopes.back().limit = limit; 706 return scopes; 707 } 708 template <typename IRUnit> 709 static SmallVector<SymbolScope, 1> collectSymbolScopes(StringAttr symbol, 710 IRUnit *limit) { 711 return {{SymbolRefAttr::get(symbol), limit}}; 712 } 713 714 /// Returns true if the given reference 'SubRef' is a sub reference of the 715 /// reference 'ref', i.e. 'ref' is a further qualified reference. 716 static bool isReferencePrefixOf(SymbolRefAttr subRef, SymbolRefAttr ref) { 717 if (ref == subRef) 718 return true; 719 720 // If the references are not pointer equal, check to see if `subRef` is a 721 // prefix of `ref`. 722 if (ref.isa<FlatSymbolRefAttr>() || 723 ref.getRootReference() != subRef.getRootReference()) 724 return false; 725 726 auto refLeafs = ref.getNestedReferences(); 727 auto subRefLeafs = subRef.getNestedReferences(); 728 return subRefLeafs.size() < refLeafs.size() && 729 subRefLeafs == refLeafs.take_front(subRefLeafs.size()); 730 } 731 732 //===----------------------------------------------------------------------===// 733 // SymbolTable::getSymbolUses 734 735 /// The implementation of SymbolTable::getSymbolUses below. 736 template <typename FromT> 737 static std::optional<SymbolTable::UseRange> getSymbolUsesImpl(FromT from) { 738 std::vector<SymbolTable::SymbolUse> uses; 739 auto walkFn = [&](SymbolTable::SymbolUse symbolUse) { 740 uses.push_back(symbolUse); 741 return WalkResult::advance(); 742 }; 743 auto result = walkSymbolUses(from, walkFn); 744 return result ? std::optional<SymbolTable::UseRange>(std::move(uses)) 745 : std::nullopt; 746 } 747 748 /// Get an iterator range for all of the uses, for any symbol, that are nested 749 /// within the given operation 'from'. This does not traverse into any nested 750 /// symbol tables, and will also only return uses on 'from' if it does not 751 /// also define a symbol table. This is because we treat the region as the 752 /// boundary of the symbol table, and not the op itself. This function returns 753 /// std::nullopt if there are any unknown operations that may potentially be 754 /// symbol tables. 755 auto SymbolTable::getSymbolUses(Operation *from) -> std::optional<UseRange> { 756 return getSymbolUsesImpl(from); 757 } 758 auto SymbolTable::getSymbolUses(Region *from) -> std::optional<UseRange> { 759 return getSymbolUsesImpl(MutableArrayRef<Region>(*from)); 760 } 761 762 //===----------------------------------------------------------------------===// 763 // SymbolTable::getSymbolUses 764 765 /// The implementation of SymbolTable::getSymbolUses below. 766 template <typename SymbolT, typename IRUnitT> 767 static std::optional<SymbolTable::UseRange> getSymbolUsesImpl(SymbolT symbol, 768 IRUnitT *limit) { 769 std::vector<SymbolTable::SymbolUse> uses; 770 for (SymbolScope &scope : collectSymbolScopes(symbol, limit)) { 771 if (!scope.walk([&](SymbolTable::SymbolUse symbolUse) { 772 if (isReferencePrefixOf(scope.symbol, symbolUse.getSymbolRef())) 773 uses.push_back(symbolUse); 774 })) 775 return std::nullopt; 776 } 777 return SymbolTable::UseRange(std::move(uses)); 778 } 779 780 /// Get all of the uses of the given symbol that are nested within the given 781 /// operation 'from', invoking the provided callback for each. This does not 782 /// traverse into any nested symbol tables. This function returns std::nullopt 783 /// if there are any unknown operations that may potentially be symbol tables. 784 auto SymbolTable::getSymbolUses(StringAttr symbol, Operation *from) 785 -> std::optional<UseRange> { 786 return getSymbolUsesImpl(symbol, from); 787 } 788 auto SymbolTable::getSymbolUses(Operation *symbol, Operation *from) 789 -> std::optional<UseRange> { 790 return getSymbolUsesImpl(symbol, from); 791 } 792 auto SymbolTable::getSymbolUses(StringAttr symbol, Region *from) 793 -> std::optional<UseRange> { 794 return getSymbolUsesImpl(symbol, from); 795 } 796 auto SymbolTable::getSymbolUses(Operation *symbol, Region *from) 797 -> std::optional<UseRange> { 798 return getSymbolUsesImpl(symbol, from); 799 } 800 801 //===----------------------------------------------------------------------===// 802 // SymbolTable::symbolKnownUseEmpty 803 804 /// The implementation of SymbolTable::symbolKnownUseEmpty below. 805 template <typename SymbolT, typename IRUnitT> 806 static bool symbolKnownUseEmptyImpl(SymbolT symbol, IRUnitT *limit) { 807 for (SymbolScope &scope : collectSymbolScopes(symbol, limit)) { 808 // Walk all of the symbol uses looking for a reference to 'symbol'. 809 if (scope.walk([&](SymbolTable::SymbolUse symbolUse) { 810 return isReferencePrefixOf(scope.symbol, symbolUse.getSymbolRef()) 811 ? WalkResult::interrupt() 812 : WalkResult::advance(); 813 }) != WalkResult::advance()) 814 return false; 815 } 816 return true; 817 } 818 819 /// Return if the given symbol is known to have no uses that are nested within 820 /// the given operation 'from'. This does not traverse into any nested symbol 821 /// tables. This function will also return false if there are any unknown 822 /// operations that may potentially be symbol tables. 823 bool SymbolTable::symbolKnownUseEmpty(StringAttr symbol, Operation *from) { 824 return symbolKnownUseEmptyImpl(symbol, from); 825 } 826 bool SymbolTable::symbolKnownUseEmpty(Operation *symbol, Operation *from) { 827 return symbolKnownUseEmptyImpl(symbol, from); 828 } 829 bool SymbolTable::symbolKnownUseEmpty(StringAttr symbol, Region *from) { 830 return symbolKnownUseEmptyImpl(symbol, from); 831 } 832 bool SymbolTable::symbolKnownUseEmpty(Operation *symbol, Region *from) { 833 return symbolKnownUseEmptyImpl(symbol, from); 834 } 835 836 //===----------------------------------------------------------------------===// 837 // SymbolTable::replaceAllSymbolUses 838 839 /// Generates a new symbol reference attribute with a new leaf reference. 840 static SymbolRefAttr generateNewRefAttr(SymbolRefAttr oldAttr, 841 FlatSymbolRefAttr newLeafAttr) { 842 if (oldAttr.isa<FlatSymbolRefAttr>()) 843 return newLeafAttr; 844 auto nestedRefs = llvm::to_vector<2>(oldAttr.getNestedReferences()); 845 nestedRefs.back() = newLeafAttr; 846 return SymbolRefAttr::get(oldAttr.getRootReference(), nestedRefs); 847 } 848 849 /// The implementation of SymbolTable::replaceAllSymbolUses below. 850 template <typename SymbolT, typename IRUnitT> 851 static LogicalResult 852 replaceAllSymbolUsesImpl(SymbolT symbol, StringAttr newSymbol, IRUnitT *limit) { 853 // Generate a new attribute to replace the given attribute. 854 FlatSymbolRefAttr newLeafAttr = FlatSymbolRefAttr::get(newSymbol); 855 for (SymbolScope &scope : collectSymbolScopes(symbol, limit)) { 856 SymbolRefAttr oldAttr = scope.symbol; 857 SymbolRefAttr newAttr = generateNewRefAttr(scope.symbol, newLeafAttr); 858 AttrTypeReplacer replacer; 859 replacer.addReplacement( 860 [&](SymbolRefAttr attr) -> std::pair<Attribute, WalkResult> { 861 // Regardless of the match, don't walk nested SymbolRefAttrs, we don't 862 // want to accidentally replace an inner reference. 863 if (attr == oldAttr) 864 return {newAttr, WalkResult::skip()}; 865 // Handle prefix matches. 866 if (isReferencePrefixOf(oldAttr, attr)) { 867 auto oldNestedRefs = oldAttr.getNestedReferences(); 868 auto nestedRefs = attr.getNestedReferences(); 869 if (oldNestedRefs.empty()) 870 return {SymbolRefAttr::get(newSymbol, nestedRefs), 871 WalkResult::skip()}; 872 873 auto newNestedRefs = llvm::to_vector<4>(nestedRefs); 874 newNestedRefs[oldNestedRefs.size() - 1] = newLeafAttr; 875 return {SymbolRefAttr::get(attr.getRootReference(), newNestedRefs), 876 WalkResult::skip()}; 877 } 878 return {attr, WalkResult::skip()}; 879 }); 880 881 auto walkFn = [&](Operation *op) -> Optional<WalkResult> { 882 replacer.replaceElementsIn(op); 883 return WalkResult::advance(); 884 }; 885 if (!scope.walkSymbolTable(walkFn)) 886 return failure(); 887 } 888 return success(); 889 } 890 891 /// Attempt to replace all uses of the given symbol 'oldSymbol' with the 892 /// provided symbol 'newSymbol' that are nested within the given operation 893 /// 'from'. This does not traverse into any nested symbol tables. If there are 894 /// any unknown operations that may potentially be symbol tables, no uses are 895 /// replaced and failure is returned. 896 LogicalResult SymbolTable::replaceAllSymbolUses(StringAttr oldSymbol, 897 StringAttr newSymbol, 898 Operation *from) { 899 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 900 } 901 LogicalResult SymbolTable::replaceAllSymbolUses(Operation *oldSymbol, 902 StringAttr newSymbol, 903 Operation *from) { 904 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 905 } 906 LogicalResult SymbolTable::replaceAllSymbolUses(StringAttr oldSymbol, 907 StringAttr newSymbol, 908 Region *from) { 909 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 910 } 911 LogicalResult SymbolTable::replaceAllSymbolUses(Operation *oldSymbol, 912 StringAttr newSymbol, 913 Region *from) { 914 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 915 } 916 917 //===----------------------------------------------------------------------===// 918 // SymbolTableCollection 919 //===----------------------------------------------------------------------===// 920 921 Operation *SymbolTableCollection::lookupSymbolIn(Operation *symbolTableOp, 922 StringAttr symbol) { 923 return getSymbolTable(symbolTableOp).lookup(symbol); 924 } 925 Operation *SymbolTableCollection::lookupSymbolIn(Operation *symbolTableOp, 926 SymbolRefAttr name) { 927 SmallVector<Operation *, 4> symbols; 928 if (failed(lookupSymbolIn(symbolTableOp, name, symbols))) 929 return nullptr; 930 return symbols.back(); 931 } 932 /// A variant of 'lookupSymbolIn' that returns all of the symbols referenced by 933 /// a given SymbolRefAttr. Returns failure if any of the nested references could 934 /// not be resolved. 935 LogicalResult 936 SymbolTableCollection::lookupSymbolIn(Operation *symbolTableOp, 937 SymbolRefAttr name, 938 SmallVectorImpl<Operation *> &symbols) { 939 auto lookupFn = [this](Operation *symbolTableOp, StringAttr symbol) { 940 return lookupSymbolIn(symbolTableOp, symbol); 941 }; 942 return lookupSymbolInImpl(symbolTableOp, name, symbols, lookupFn); 943 } 944 945 /// Returns the operation registered with the given symbol name within the 946 /// closest parent operation of, or including, 'from' with the 947 /// 'OpTrait::SymbolTable' trait. Returns nullptr if no valid symbol was 948 /// found. 949 Operation *SymbolTableCollection::lookupNearestSymbolFrom(Operation *from, 950 StringAttr symbol) { 951 Operation *symbolTableOp = SymbolTable::getNearestSymbolTable(from); 952 return symbolTableOp ? lookupSymbolIn(symbolTableOp, symbol) : nullptr; 953 } 954 Operation * 955 SymbolTableCollection::lookupNearestSymbolFrom(Operation *from, 956 SymbolRefAttr symbol) { 957 Operation *symbolTableOp = SymbolTable::getNearestSymbolTable(from); 958 return symbolTableOp ? lookupSymbolIn(symbolTableOp, symbol) : nullptr; 959 } 960 961 /// Lookup, or create, a symbol table for an operation. 962 SymbolTable &SymbolTableCollection::getSymbolTable(Operation *op) { 963 auto it = symbolTables.try_emplace(op, nullptr); 964 if (it.second) 965 it.first->second = std::make_unique<SymbolTable>(op); 966 return *it.first->second; 967 } 968 969 //===----------------------------------------------------------------------===// 970 // SymbolUserMap 971 //===----------------------------------------------------------------------===// 972 973 SymbolUserMap::SymbolUserMap(SymbolTableCollection &symbolTable, 974 Operation *symbolTableOp) 975 : symbolTable(symbolTable) { 976 // Walk each of the symbol tables looking for discardable callgraph nodes. 977 SmallVector<Operation *> symbols; 978 auto walkFn = [&](Operation *symbolTableOp, bool allUsesVisible) { 979 for (Operation &nestedOp : symbolTableOp->getRegion(0).getOps()) { 980 auto symbolUses = SymbolTable::getSymbolUses(&nestedOp); 981 assert(symbolUses && "expected uses to be valid"); 982 983 for (const SymbolTable::SymbolUse &use : *symbolUses) { 984 symbols.clear(); 985 (void)symbolTable.lookupSymbolIn(symbolTableOp, use.getSymbolRef(), 986 symbols); 987 for (Operation *symbolOp : symbols) 988 symbolToUsers[symbolOp].insert(use.getUser()); 989 } 990 } 991 }; 992 // We just set `allSymUsesVisible` to false here because it isn't necessary 993 // for building the user map. 994 SymbolTable::walkSymbolTables(symbolTableOp, /*allSymUsesVisible=*/false, 995 walkFn); 996 } 997 998 void SymbolUserMap::replaceAllUsesWith(Operation *symbol, 999 StringAttr newSymbolName) { 1000 auto it = symbolToUsers.find(symbol); 1001 if (it == symbolToUsers.end()) 1002 return; 1003 1004 // Replace the uses within the users of `symbol`. 1005 for (Operation *user : it->second) 1006 (void)SymbolTable::replaceAllSymbolUses(symbol, newSymbolName, user); 1007 1008 // Move the current users of `symbol` to the new symbol if it is in the 1009 // symbol table. 1010 Operation *newSymbol = 1011 symbolTable.lookupSymbolIn(symbol->getParentOp(), newSymbolName); 1012 if (newSymbol != symbol) { 1013 // Transfer over the users to the new symbol. The reference to the old one 1014 // is fetched again as the iterator is invalidated during the insertion. 1015 auto newIt = symbolToUsers.try_emplace(newSymbol, SetVector<Operation *>{}); 1016 auto oldIt = symbolToUsers.find(symbol); 1017 assert(oldIt != symbolToUsers.end() && "missing old users list"); 1018 if (newIt.second) 1019 newIt.first->second = std::move(oldIt->second); 1020 else 1021 newIt.first->second.set_union(oldIt->second); 1022 symbolToUsers.erase(oldIt); 1023 } 1024 } 1025 1026 //===----------------------------------------------------------------------===// 1027 // Visibility parsing implementation. 1028 //===----------------------------------------------------------------------===// 1029 1030 ParseResult impl::parseOptionalVisibilityKeyword(OpAsmParser &parser, 1031 NamedAttrList &attrs) { 1032 StringRef visibility; 1033 if (parser.parseOptionalKeyword(&visibility, {"public", "private", "nested"})) 1034 return failure(); 1035 1036 StringAttr visibilityAttr = parser.getBuilder().getStringAttr(visibility); 1037 attrs.push_back(parser.getBuilder().getNamedAttr( 1038 SymbolTable::getVisibilityAttrName(), visibilityAttr)); 1039 return success(); 1040 } 1041 1042 //===----------------------------------------------------------------------===// 1043 // Symbol Interfaces 1044 //===----------------------------------------------------------------------===// 1045 1046 /// Include the generated symbol interfaces. 1047 #include "mlir/IR/SymbolInterfaces.cpp.inc" 1048