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