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