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