1 //===- SymbolTable.cpp - MLIR Symbol Table Class --------------------------===// 2 // 3 // Copyright 2019 The MLIR Authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // ============================================================================= 17 18 #include "mlir/IR/SymbolTable.h" 19 #include "llvm/ADT/SmallString.h" 20 21 using namespace mlir; 22 23 /// Return true if the given operation is unknown and may potentially define a 24 /// symbol table. 25 static bool isPotentiallyUnknownSymbolTable(Operation *op) { 26 return !op->getDialect() && op->getNumRegions() == 1; 27 } 28 29 //===----------------------------------------------------------------------===// 30 // SymbolTable 31 //===----------------------------------------------------------------------===// 32 33 /// Build a symbol table with the symbols within the given operation. 34 SymbolTable::SymbolTable(Operation *symbolTableOp) 35 : symbolTableOp(symbolTableOp) { 36 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>() && 37 "expected operation to have SymbolTable trait"); 38 assert(symbolTableOp->getNumRegions() == 1 && 39 "expected operation to have a single region"); 40 assert(has_single_element(symbolTableOp->getRegion(0)) && 41 "expected operation to have a single block"); 42 43 for (auto &op : symbolTableOp->getRegion(0).front()) { 44 auto nameAttr = op.getAttrOfType<StringAttr>(getSymbolAttrName()); 45 if (!nameAttr) 46 continue; 47 48 auto inserted = symbolTable.insert({nameAttr.getValue(), &op}); 49 (void)inserted; 50 assert(inserted.second && 51 "expected region to contain uniquely named symbol operations"); 52 } 53 } 54 55 /// Look up a symbol with the specified name, returning null if no such name 56 /// exists. Names never include the @ on them. 57 Operation *SymbolTable::lookup(StringRef name) const { 58 return symbolTable.lookup(name); 59 } 60 61 /// Erase the given symbol from the table. 62 void SymbolTable::erase(Operation *symbol) { 63 auto nameAttr = symbol->getAttrOfType<StringAttr>(getSymbolAttrName()); 64 assert(nameAttr && "expected valid 'name' attribute"); 65 assert(symbol->getParentOp() == symbolTableOp && 66 "expected this operation to be inside of the operation with this " 67 "SymbolTable"); 68 69 auto it = symbolTable.find(nameAttr.getValue()); 70 if (it != symbolTable.end() && it->second == symbol) { 71 symbolTable.erase(it); 72 symbol->erase(); 73 } 74 } 75 76 /// Insert a new symbol into the table and associated operation, and rename it 77 /// as necessary to avoid collisions. 78 void SymbolTable::insert(Operation *symbol, Block::iterator insertPt) { 79 auto nameAttr = symbol->getAttrOfType<StringAttr>(getSymbolAttrName()); 80 assert(nameAttr && "expected valid 'name' attribute"); 81 82 auto &body = symbolTableOp->getRegion(0).front(); 83 if (insertPt == Block::iterator() || insertPt == body.end()) 84 insertPt = Block::iterator(body.getTerminator()); 85 86 assert(insertPt->getParentOp() == symbolTableOp && 87 "expected insertPt to be in the associated module operation"); 88 89 body.getOperations().insert(insertPt, symbol); 90 91 // Add this symbol to the symbol table, uniquing the name if a conflict is 92 // detected. 93 if (symbolTable.insert({nameAttr.getValue(), symbol}).second) 94 return; 95 96 // If a conflict was detected, then the symbol will not have been added to 97 // the symbol table. Try suffixes until we get to a unique name that works. 98 SmallString<128> nameBuffer(nameAttr.getValue()); 99 unsigned originalLength = nameBuffer.size(); 100 101 // Iteratively try suffixes until we find one that isn't used. 102 do { 103 nameBuffer.resize(originalLength); 104 nameBuffer += '_'; 105 nameBuffer += std::to_string(uniquingCounter++); 106 } while (!symbolTable.insert({nameBuffer, symbol}).second); 107 symbol->setAttr(getSymbolAttrName(), 108 StringAttr::get(nameBuffer, symbolTableOp->getContext())); 109 } 110 111 /// Returns the operation registered with the given symbol name with the 112 /// regions of 'symbolTableOp'. 'symbolTableOp' is required to be an operation 113 /// with the 'OpTrait::SymbolTable' trait. Returns nullptr if no valid symbol 114 /// was found. 115 Operation *SymbolTable::lookupSymbolIn(Operation *symbolTableOp, 116 StringRef symbol) { 117 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>()); 118 119 // Look for a symbol with the given name. 120 for (auto &block : symbolTableOp->getRegion(0)) { 121 for (auto &op : block) { 122 auto nameAttr = op.template getAttrOfType<StringAttr>( 123 mlir::SymbolTable::getSymbolAttrName()); 124 if (nameAttr && nameAttr.getValue() == symbol) 125 return &op; 126 } 127 } 128 return nullptr; 129 } 130 131 /// Returns the operation registered with the given symbol name within the 132 /// closes parent operation with the 'OpTrait::SymbolTable' trait. Returns 133 /// nullptr if no valid symbol was found. 134 Operation *SymbolTable::lookupNearestSymbolFrom(Operation *from, 135 StringRef symbol) { 136 assert(from && "expected valid operation"); 137 while (!from->hasTrait<OpTrait::SymbolTable>()) { 138 from = from->getParentOp(); 139 140 // Check that this is a valid op and isn't an unknown symbol table. 141 if (!from || isPotentiallyUnknownSymbolTable(from)) 142 return nullptr; 143 } 144 return lookupSymbolIn(from, symbol); 145 } 146 147 //===----------------------------------------------------------------------===// 148 // SymbolTable Trait Types 149 //===----------------------------------------------------------------------===// 150 151 LogicalResult OpTrait::impl::verifySymbolTable(Operation *op) { 152 if (op->getNumRegions() != 1) 153 return op->emitOpError() 154 << "Operations with a 'SymbolTable' must have exactly one region"; 155 if (!has_single_element(op->getRegion(0))) 156 return op->emitOpError() 157 << "Operations with a 'SymbolTable' must have exactly one block"; 158 159 // Check that all symbols are uniquely named within child regions. 160 llvm::StringMap<Location> nameToOrigLoc; 161 for (auto &block : op->getRegion(0)) { 162 for (auto &op : block) { 163 // Check for a symbol name attribute. 164 auto nameAttr = 165 op.getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()); 166 if (!nameAttr) 167 continue; 168 169 // Try to insert this symbol into the table. 170 auto it = nameToOrigLoc.try_emplace(nameAttr.getValue(), op.getLoc()); 171 if (!it.second) 172 return op.emitError() 173 .append("redefinition of symbol named '", nameAttr.getValue(), "'") 174 .attachNote(it.first->second) 175 .append("see existing symbol definition here"); 176 } 177 } 178 return success(); 179 } 180 181 LogicalResult OpTrait::impl::verifySymbol(Operation *op) { 182 if (!op->getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName())) 183 return op->emitOpError() << "requires string attribute '" 184 << mlir::SymbolTable::getSymbolAttrName() << "'"; 185 return success(); 186 } 187 188 //===----------------------------------------------------------------------===// 189 // Symbol Use Lists 190 //===----------------------------------------------------------------------===// 191 192 /// Walk all of the symbol references within the given operation, invoking the 193 /// provided callback for each found use. The callbacks takes as arguments: the 194 /// use of the symbol, and the nested access chain to the attribute within the 195 /// operation dictionary. An access chain is a set of indices into nested 196 /// container attributes. For example, a symbol use in an attribute dictionary 197 /// that looks like the following: 198 /// 199 /// {use = [{other_attr, @symbol}]} 200 /// 201 /// May have the following access chain: 202 /// 203 /// [0, 0, 1] 204 /// 205 static WalkResult walkSymbolRefs( 206 Operation *op, 207 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 208 // Check to see if the operation has any attributes. 209 DictionaryAttr attrDict = op->getAttrList().getDictionary(); 210 if (!attrDict) 211 return WalkResult::advance(); 212 213 // A worklist of a container attribute and the current index into the held 214 // attribute list. 215 SmallVector<Attribute, 1> attrWorklist(1, attrDict); 216 SmallVector<int, 1> curAccessChain(1, /*Value=*/-1); 217 218 // Process the symbol references within the given nested attribute range. 219 auto processAttrs = [&](int &index, auto attrRange) -> WalkResult { 220 for (Attribute attr : llvm::drop_begin(attrRange, index)) { 221 /// Check for a nested container attribute, these will also need to be 222 /// walked. 223 if (attr.isa<ArrayAttr>() || attr.isa<DictionaryAttr>()) { 224 attrWorklist.push_back(attr); 225 curAccessChain.push_back(-1); 226 return WalkResult::advance(); 227 } 228 229 // Invoke the provided callback if we find a symbol use and check for a 230 // requested interrupt. 231 if (auto symbolRef = attr.dyn_cast<SymbolRefAttr>()) 232 if (callback({op, symbolRef}, curAccessChain).wasInterrupted()) 233 return WalkResult::interrupt(); 234 235 // Make sure to keep the index counter in sync. 236 ++index; 237 } 238 239 // Pop this container attribute from the worklist. 240 attrWorklist.pop_back(); 241 curAccessChain.pop_back(); 242 return WalkResult::advance(); 243 }; 244 245 WalkResult result = WalkResult::advance(); 246 do { 247 Attribute attr = attrWorklist.back(); 248 int &index = curAccessChain.back(); 249 ++index; 250 251 // Process the given attribute, which is guaranteed to be a container. 252 if (auto dict = attr.dyn_cast<DictionaryAttr>()) 253 result = processAttrs(index, make_second_range(dict.getValue())); 254 else 255 result = processAttrs(index, attr.cast<ArrayAttr>().getValue()); 256 } while (!attrWorklist.empty() && !result.wasInterrupted()); 257 return result; 258 } 259 260 /// Walk all of the uses, for any symbol, that are nested within the given 261 /// operation 'from', invoking the provided callback for each. This does not 262 /// traverse into any nested symbol tables, and will also only return uses on 263 /// 'from' if it does not also define a symbol table. 264 static Optional<WalkResult> walkSymbolUses( 265 Operation *from, 266 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 267 // If from is not a symbol table, check for uses. A symbol table defines a new 268 // scope, so we can't walk the attributes from the symbol table op. 269 if (!from->hasTrait<OpTrait::SymbolTable>()) { 270 if (walkSymbolRefs(from, callback).wasInterrupted()) 271 return WalkResult::interrupt(); 272 } 273 274 SmallVector<Region *, 1> worklist; 275 worklist.reserve(from->getNumRegions()); 276 for (Region ®ion : from->getRegions()) 277 worklist.push_back(®ion); 278 279 while (!worklist.empty()) { 280 Region *region = worklist.pop_back_val(); 281 for (Block &block : *region) { 282 for (Operation &op : block) { 283 if (walkSymbolRefs(&op, callback).wasInterrupted()) 284 return WalkResult::interrupt(); 285 286 // If this operation has regions, and it as well as its dialect aren't 287 // registered then conservatively fail. The operation may define a 288 // symbol table, so we can't opaquely know if we should traverse to find 289 // nested uses. 290 if (isPotentiallyUnknownSymbolTable(&op)) 291 return llvm::None; 292 293 // If this op defines a new symbol table scope, we can't traverse. Any 294 // symbol references nested within 'op' are different semantically. 295 if (!op.hasTrait<OpTrait::SymbolTable>()) { 296 for (Region ®ion : op.getRegions()) 297 worklist.push_back(®ion); 298 } 299 } 300 } 301 } 302 return WalkResult::advance(); 303 } 304 305 /// Get an iterator range for all of the uses, for any symbol, that are nested 306 /// within the given operation 'from'. This does not traverse into any nested 307 /// symbol tables, and will also only return uses on 'from' if it does not 308 /// also define a symbol table. This is because we treat the region as the 309 /// boundary of the symbol table, and not the op itself. This function returns 310 /// None if there are any unknown operations that may potentially be symbol 311 /// tables. 312 auto SymbolTable::getSymbolUses(Operation *from) -> Optional<UseRange> { 313 std::vector<SymbolUse> uses; 314 Optional<WalkResult> result = 315 walkSymbolUses(from, [&](SymbolUse symbolUse, ArrayRef<int>) { 316 uses.push_back(symbolUse); 317 return WalkResult::advance(); 318 }); 319 return result ? Optional<UseRange>(std::move(uses)) : Optional<UseRange>(); 320 } 321 322 /// Get all of the uses of the given symbol that are nested within the given 323 /// operation 'from', invoking the provided callback for each. This does not 324 /// traverse into any nested symbol tables, and will also only return uses on 325 /// 'from' if it does not also define a symbol table. This is because we treat 326 /// the region as the boundary of the symbol table, and not the op itself. This 327 /// function returns None if there are any unknown operations that may 328 /// potentially be symbol tables. 329 auto SymbolTable::getSymbolUses(StringRef symbol, Operation *from) 330 -> Optional<UseRange> { 331 SymbolRefAttr symbolRefAttr = SymbolRefAttr::get(symbol, from->getContext()); 332 333 std::vector<SymbolUse> uses; 334 Optional<WalkResult> result = 335 walkSymbolUses(from, [&](SymbolUse symbolUse, ArrayRef<int>) { 336 if (symbolRefAttr == symbolUse.getSymbolRef()) 337 uses.push_back(symbolUse); 338 return WalkResult::advance(); 339 }); 340 return result ? Optional<UseRange>(std::move(uses)) : Optional<UseRange>(); 341 } 342 343 /// Return if the given symbol is known to have no uses that are nested within 344 /// the given operation 'from'. This does not traverse into any nested symbol 345 /// tables, and will also only count uses on 'from' if it does not also define 346 /// a symbol table. This is because we treat the region as the boundary of the 347 /// symbol table, and not the op itself. This function will also return false if 348 /// there are any unknown operations that may potentially be symbol tables. 349 bool SymbolTable::symbolKnownUseEmpty(StringRef symbol, Operation *from) { 350 SymbolRefAttr symbolRefAttr = SymbolRefAttr::get(symbol, from->getContext()); 351 352 // Walk all of the symbol uses looking for a reference to 'symbol'. 353 Optional<WalkResult> walkResult = 354 walkSymbolUses(from, [&](SymbolUse symbolUse, ArrayRef<int>) { 355 return symbolUse.getSymbolRef() == symbolRefAttr 356 ? WalkResult::interrupt() 357 : WalkResult::advance(); 358 }); 359 return walkResult && !walkResult->wasInterrupted(); 360 } 361 362 /// Rebuild the given attribute container after replacing all references to a 363 /// symbol with `newSymAttr`. 364 static Attribute rebuildAttrAfterRAUW(Attribute container, 365 ArrayRef<SmallVector<int, 1>> accesses, 366 SymbolRefAttr newSymAttr, 367 unsigned depth) { 368 // Given a range of Attributes, update the ones referred to by the given 369 // access chains to point to the new symbol attribute. 370 auto updateAttrs = [&](auto &&attrRange) { 371 auto attrBegin = std::begin(attrRange); 372 for (unsigned i = 0, e = accesses.size(); i != e;) { 373 ArrayRef<int> access = accesses[i]; 374 Attribute &attr = *std::next(attrBegin, access[depth]); 375 376 // Check to see if this is a leaf access, i.e. a SymbolRef. 377 if (access.size() == depth + 1) { 378 attr = newSymAttr; 379 ++i; 380 continue; 381 } 382 383 // Otherwise, this is a container. Collect all of the accesses for this 384 // index and recurse. The recursion here is bounded by the size of the 385 // largest access array. 386 auto nestedAccesses = 387 accesses.drop_front(i).take_while([&](ArrayRef<int> nextAccess) { 388 return nextAccess.size() > depth + 1 && 389 nextAccess[depth] == access[depth]; 390 }); 391 attr = rebuildAttrAfterRAUW(attr, nestedAccesses, newSymAttr, depth + 1); 392 393 // Skip over all of the accesses that refer to the nested container. 394 i += nestedAccesses.size(); 395 } 396 }; 397 398 if (auto dictAttr = container.dyn_cast<DictionaryAttr>()) { 399 auto newAttrs = llvm::to_vector<4>(dictAttr.getValue()); 400 updateAttrs(make_second_range(newAttrs)); 401 return DictionaryAttr::get(newAttrs, dictAttr.getContext()); 402 } 403 auto newAttrs = llvm::to_vector<4>(container.cast<ArrayAttr>().getValue()); 404 updateAttrs(newAttrs); 405 return ArrayAttr::get(newAttrs, container.getContext()); 406 } 407 408 /// Attempt to replace all uses of the given symbol 'oldSymbol' with the 409 /// provided symbol 'newSymbol' that are nested within the given operation 410 /// 'from'. This does not traverse into any nested symbol tables, and will 411 /// also only replace uses on 'from' if it does not also define a symbol 412 /// table. This is because we treat the region as the boundary of the symbol 413 /// table, and not the op itself. If there are any unknown operations that may 414 /// potentially be symbol tables, no uses are replaced and failure is returned. 415 LogicalResult SymbolTable::replaceAllSymbolUses(StringRef oldSymbol, 416 StringRef newSymbol, 417 Operation *from) { 418 SymbolRefAttr oldAttr = SymbolRefAttr::get(oldSymbol, from->getContext()); 419 SymbolRefAttr newSymAttr = SymbolRefAttr::get(newSymbol, from->getContext()); 420 421 // A collection of operations along with their new attribute dictionary. 422 std::vector<std::pair<Operation *, DictionaryAttr>> updatedAttrDicts; 423 424 // The current operation, and its old symbol access chains, being processed. 425 Operation *curOp = nullptr; 426 SmallVector<SmallVector<int, 1>, 1> accessChains; 427 428 // Generate a new attribute dictionary for the current operation by replacing 429 // references to the old symbol. 430 auto generateNewAttrDict = [&] { 431 auto newAttrDict = 432 rebuildAttrAfterRAUW(curOp->getAttrList().getDictionary(), accessChains, 433 newSymAttr, /*depth=*/0); 434 return newAttrDict.cast<DictionaryAttr>(); 435 }; 436 437 // Walk the symbol uses collecting uses of the old symbol. 438 auto walkFn = [&](SymbolTable::SymbolUse symbolUse, 439 ArrayRef<int> accessChain) { 440 if (symbolUse.getSymbolRef() != oldAttr) 441 return WalkResult::advance(); 442 443 // If there was a previous operation, generate a new attribute dict for it. 444 // This means that we've finished processing the current operation, so 445 // generate a new dictionary for it. 446 if (curOp && symbolUse.getUser() != curOp) { 447 updatedAttrDicts.push_back({curOp, generateNewAttrDict()}); 448 accessChains.clear(); 449 } 450 451 // Record this access. 452 curOp = symbolUse.getUser(); 453 accessChains.push_back(llvm::to_vector<1>(accessChain)); 454 return WalkResult::advance(); 455 }; 456 if (!walkSymbolUses(from, walkFn)) 457 return failure(); 458 459 // Update the attribute dictionaries as necessary. 460 for (auto &it : updatedAttrDicts) 461 it.first->setAttrs(it.second); 462 463 // Check to see if we have a dangling op that needs to be processed. 464 if (curOp) 465 curOp->setAttrs(generateNewAttrDict()); 466 467 return success(); 468 } 469