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