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