12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringSwitch.h"
43 assert(within->
isAncestor(symbol) &&
"expected 'within' to be an ancestor");
47 results.push_back(leafRef);
51 if (within == symbolTableOp)
56 StringAttr symbolNameId =
63 StringAttr symbolTableName =
getNameIfSymbol(symbolTableOp, symbolNameId);
69 if (symbolTableOp == within)
71 nestedRefs.insert(nestedRefs.begin(),
80 static std::optional<WalkResult>
84 while (!worklist.empty()) {
85 for (
Operation &op : worklist.pop_back_val()->getOps()) {
86 std::optional<WalkResult> result = callback(&op);
93 for (
Region ®ion : op.getRegions())
94 worklist.push_back(®ion);
104 static std::optional<WalkResult>
107 std::optional<WalkResult> result = callback(op);
119 : symbolTableOp(symbolTableOp) {
121 "expected operation to have SymbolTable trait");
123 "expected operation to have a single region");
124 assert(llvm::hasSingleElement(symbolTableOp->
getRegion(0)) &&
125 "expected operation to have a single block");
134 auto inserted = symbolTable.insert({name, &op});
136 assert(inserted.second &&
137 "expected region to contain uniquely named symbol operations");
147 return symbolTable.lookup(name);
152 assert(name &&
"expected valid 'name' attribute");
154 "expected this operation to be inside of the operation with this "
157 auto it = symbolTable.find(name);
158 if (it != symbolTable.end() && it->second == op)
159 symbolTable.erase(it);
181 assert((insertPt == body.end() ||
182 insertPt->getParentOp() == symbolTableOp) &&
183 "expected insertPt to be in the associated module operation");
188 insertPt = std::prev(body.end());
190 body.getOperations().insert(insertPt, symbol);
193 "symbol is already inserted in another op");
198 if (symbolTable.insert({name, symbol}).second)
201 if (symbolTable.lookup(name) == symbol)
207 [&](StringRef candidate) {
209 .insert({StringAttr::get(context, candidate), symbol})
213 setSymbolName(symbol, nameBuffer);
214 return getSymbolName(symbol);
217 LogicalResult SymbolTable::rename(StringAttr from, StringAttr to) {
226 assert(from &&
"expected valid 'name' attribute");
228 "expected this operation to be inside of the operation with this "
230 assert(
lookup(from) == op &&
"current name does not resolve to op");
231 assert(
lookup(to) ==
nullptr &&
"new name already exists");
242 assert(
lookup(to) == op &&
"new name does not resolve to renamed op");
243 assert(
lookup(from) ==
nullptr &&
"old name still exists");
250 return rename(from, toAttr);
255 return rename(op, toAttr);
258 FailureOr<StringAttr>
268 prefix.push_back(
'_');
271 auto lookupNewName = [&](
SymbolTable *st) {
return st->lookup(newName); };
272 if (!lookupNewName(
this) && llvm::none_of(others, lookupNewName)) {
279 if (failed(
rename(oldName, newName)))
284 FailureOr<StringAttr>
287 assert(from &&
"expected valid 'name' attribute");
294 assert(name &&
"expected valid symbol name");
329 "unknown symbol visibility kind");
338 assert(from &&
"expected valid operation");
362 SymbolOpInterface symbol = dyn_cast<SymbolOpInterface>(op);
363 allSymUsesVisible |= !symbol || symbol.isPrivate();
367 allSymUsesVisible =
true;
371 for (
Block &block : region)
378 callback(op, allSymUsesVisible);
395 for (
auto &op : region.
front())
401 SymbolRefAttr symbol) {
403 if (failed(
lookupSymbolIn(symbolTableOp, symbol, resolvedSymbols)))
405 return resolvedSymbols.back();
411 Operation *symbolTableOp, SymbolRefAttr symbol,
417 symbolTableOp = lookupSymbolFn(symbolTableOp, symbol.getRootReference());
420 symbols.push_back(symbolTableOp);
424 if (nestedRefs.empty())
434 symbolTableOp = lookupSymbolFn(symbolTableOp, ref.
getAttr());
437 symbols.push_back(symbolTableOp);
439 symbols.push_back(lookupSymbolFn(symbolTableOp, symbol.getLeafReference()));
440 return success(symbols.back());
446 auto lookupFn = [](
Operation *symbolTableOp, StringAttr symbol) {
458 return symbolTableOp ?
lookupSymbolIn(symbolTableOp, symbol) :
nullptr;
461 SymbolRefAttr symbol) {
463 return symbolTableOp ?
lookupSymbolIn(symbolTableOp, symbol) :
nullptr;
468 switch (visibility) {
470 return os <<
"public";
472 return os <<
"private";
474 return os <<
"nested";
476 llvm_unreachable(
"Unexpected visibility");
486 <<
"Operations with a 'SymbolTable' must have exactly one region";
487 if (!llvm::hasSingleElement(op->
getRegion(0)))
489 <<
"Operations with a 'SymbolTable' must have exactly one block";
494 for (
auto &op : block) {
502 auto it = nameToOrigLoc.try_emplace(nameAttr, op.
getLoc());
505 .
append(
"redefinition of symbol named '", nameAttr.getValue(),
"'")
506 .attachNote(it.first->second)
507 .
append(
"see existing symbol definition here");
513 auto verifySymbolUserFn = [&](
Operation *op) -> std::optional<WalkResult> {
514 if (SymbolUserOpInterface user = dyn_cast<SymbolUserOpInterface>(op))
515 return WalkResult(user.verifySymbolUses(symbolTable));
519 std::optional<WalkResult> result =
521 return success(result && !result->wasInterrupted());
527 return op->
emitOpError() <<
"requires string attribute '"
532 StringAttr visStrAttr = llvm::dyn_cast<StringAttr>(vis);
534 return op->
emitOpError() <<
"requires visibility attribute '"
536 <<
"' to be a string attribute, but got " << vis;
539 visStrAttr.getValue()))
541 <<
"visibility expected to be one of [\"public\", \"private\", "
542 "\"nested\"], but got "
559 [&](SymbolRefAttr symbolRef) {
560 if (callback({op, symbolRef}).wasInterrupted())
571 static std::optional<WalkResult>
575 [&](
Operation *op) -> std::optional<WalkResult> {
587 static std::optional<WalkResult>
619 template <
typename CallbackT,
620 std::enable_if_t<!std::is_same<
621 typename llvm::function_traits<CallbackT>::result_t,
622 void>::value> * =
nullptr>
623 std::optional<WalkResult>
walk(CallbackT cback) {
624 if (
Region *region = llvm::dyn_cast_if_present<Region *>(limit))
630 template <
typename CallbackT,
631 std::enable_if_t<std::is_same<
632 typename llvm::function_traits<CallbackT>::result_t,
633 void>::value> * =
nullptr>
634 std::optional<WalkResult>
walk(CallbackT cback) {
642 template <
typename CallbackT>
644 if (
Region *region = llvm::dyn_cast_if_present<Region *>(limit))
650 SymbolRefAttr symbol;
670 if (limitAncestor == symbol) {
679 limitAncestors.insert(limitAncestor);
680 }
while ((limitAncestor = limitAncestor->
getParentOp()));
685 if (limitAncestors.count(commonAncestor))
687 }
while ((commonAncestor = commonAncestor->
getParentOp()));
688 assert(commonAncestor &&
"'limit' and 'symbol' have no common ancestor");
693 bool collectedAllReferences = succeeded(
697 if (commonAncestor == limit) {
703 for (
size_t i = 0, e = references.size(); i != e;
706 scopes.push_back({references[i], &limitIt->
getRegion(0)});
714 if (!collectedAllReferences)
716 return {{references.back(), limit}};
725 scopes.back().limit = limit;
738 scopes.push_back({symbolRef, ®ion});
750 if (llvm::isa<FlatSymbolRefAttr>(ref) ||
751 ref.getRootReference() != subRef.getRootReference())
754 auto refLeafs = ref.getNestedReferences();
755 auto subRefLeafs = subRef.getNestedReferences();
756 return subRefLeafs.size() < refLeafs.size() &&
757 subRefLeafs == refLeafs.take_front(subRefLeafs.size());
764 template <
typename FromT>
766 std::vector<SymbolTable::SymbolUse> uses;
768 uses.push_back(symbolUse);
772 return result ? std::optional<SymbolTable::UseRange>(std::move(uses))
794 template <
typename SymbolT,
typename IRUnitT>
797 std::vector<SymbolTable::SymbolUse> uses;
800 if (isReferencePrefixOf(scope.symbol, symbolUse.getSymbolRef()))
801 uses.push_back(symbolUse);
813 -> std::optional<UseRange> {
817 -> std::optional<UseRange> {
821 -> std::optional<UseRange> {
825 -> std::optional<UseRange> {
833 template <
typename SymbolT,
typename IRUnitT>
838 return isReferencePrefixOf(scope.symbol, symbolUse.getSymbolRef())
839 ? WalkResult::interrupt()
840 : WalkResult::advance();
870 if (llvm::isa<FlatSymbolRefAttr>(oldAttr))
872 auto nestedRefs = llvm::to_vector<2>(oldAttr.getNestedReferences());
873 nestedRefs.back() = newLeafAttr;
878 template <
typename SymbolT,
typename IRUnitT>
884 SymbolRefAttr oldAttr = scope.symbol;
888 [&](SymbolRefAttr attr) -> std::pair<Attribute, WalkResult> {
895 auto oldNestedRefs = oldAttr.getNestedReferences();
896 auto nestedRefs = attr.getNestedReferences();
897 if (oldNestedRefs.empty())
901 auto newNestedRefs = llvm::to_vector<4>(nestedRefs);
902 newNestedRefs[oldNestedRefs.size() - 1] = newLeafAttr;
909 auto walkFn = [&](
Operation *op) -> std::optional<WalkResult> {
913 if (!scope.walkSymbolTable(walkFn))
925 StringAttr newSymbol,
930 StringAttr newSymbol,
935 StringAttr newSymbol,
940 StringAttr newSymbol,
954 SymbolRefAttr name) {
958 return symbols.back();
967 auto lookupFn = [
this](
Operation *symbolTableOp, StringAttr symbol) {
980 return symbolTableOp ?
lookupSymbolIn(symbolTableOp, symbol) :
nullptr;
984 SymbolRefAttr symbol) {
986 return symbolTableOp ?
lookupSymbolIn(symbolTableOp, symbol) :
nullptr;
991 auto it = symbolTables.try_emplace(op,
nullptr);
993 it.first->second = std::make_unique<SymbolTable>(op);
994 return *it.first->second;
1002 StringAttr symbol) {
1003 return getSymbolTable(symbolTableOp).
lookup(symbol);
1013 SymbolRefAttr name) {
1017 return symbols.back();
1021 Operation *symbolTableOp, SymbolRefAttr name,
1023 auto lookupFn = [
this](
Operation *symbolTableOp, StringAttr symbol) {
1030 LockedSymbolTableCollection::getSymbolTable(
Operation *symbolTableOp) {
1034 llvm::sys::SmartScopedReader<true> lock(mutex);
1035 auto it = collection.symbolTables.find(symbolTableOp);
1036 if (it != collection.symbolTables.end())
1041 auto symbolTable = std::make_unique<SymbolTable>(symbolTableOp);
1043 llvm::sys::SmartScopedWriter<true> lock(mutex);
1044 return *collection.symbolTables
1045 .insert({symbolTableOp, std::move(symbolTable)})
1055 : symbolTable(symbolTable) {
1058 auto walkFn = [&](
Operation *symbolTableOp,
bool allUsesVisible) {
1061 assert(symbolUses &&
"expected uses to be valid");
1065 (void)symbolTable.
lookupSymbolIn(symbolTableOp, use.getSymbolRef(),
1068 symbolToUsers[symbolOp].insert(use.getUser());
1079 StringAttr newSymbolName) {
1080 auto it = symbolToUsers.find(symbol);
1081 if (it == symbolToUsers.end())
1092 if (newSymbol != symbol) {
1096 auto oldIt = symbolToUsers.find(symbol);
1097 assert(oldIt != symbolToUsers.end() &&
"missing old users list");
1099 newIt.first->second = std::move(oldIt->second);
1101 newIt.first->second.set_union(oldIt->second);
1102 symbolToUsers.erase(oldIt);
1112 StringRef visibility;
1127 #include "mlir/IR/SymbolInterfaces.cpp.inc"
static MLIRContext * getContext(OpFoldResult val)
static std::optional< WalkResult > walkSymbolTable(MutableArrayRef< Region > regions, function_ref< std::optional< WalkResult >(Operation *)> callback)
Walk all of the operations within the given set of regions, without traversing into any nested symbol...
static LogicalResult collectValidReferencesFor(Operation *symbol, StringAttr symbolName, Operation *within, SmallVectorImpl< SymbolRefAttr > &results)
Computes the nested symbol reference attribute for the symbol 'symbolName' that are usable within the...
static bool symbolKnownUseEmptyImpl(SymbolT symbol, IRUnitT *limit)
The implementation of SymbolTable::symbolKnownUseEmpty below.
static SmallVector< SymbolScope, 2 > collectSymbolScopes(Operation *symbol, Operation *limit)
Collect all of the symbol scopes from 'symbol' to (inclusive) 'limit'.
static WalkResult walkSymbolRefs(Operation *op, function_ref< WalkResult(SymbolTable::SymbolUse)> callback)
Walk all of the symbol references within the given operation, invoking the provided callback for each...
static StringAttr getNameIfSymbol(Operation *op)
Returns the string name of the given symbol, or null if this is not a symbol.
static bool isReferencePrefixOf(SymbolRefAttr subRef, SymbolRefAttr ref)
Returns true if the given reference 'SubRef' is a sub reference of the reference 'ref',...
static std::optional< WalkResult > walkSymbolUses(MutableArrayRef< Region > regions, function_ref< WalkResult(SymbolTable::SymbolUse)> callback)
Walk all of the uses, for any symbol, that are nested within the given regions, invoking the provided...
static SymbolRefAttr generateNewRefAttr(SymbolRefAttr oldAttr, FlatSymbolRefAttr newLeafAttr)
Generates a new symbol reference attribute with a new leaf reference.
static LogicalResult replaceAllSymbolUsesImpl(SymbolT symbol, StringAttr newSymbol, IRUnitT *limit)
The implementation of SymbolTable::replaceAllSymbolUses below.
static LogicalResult lookupSymbolInImpl(Operation *symbolTableOp, SymbolRefAttr symbol, SmallVectorImpl< Operation * > &symbols, function_ref< Operation *(Operation *, StringAttr)> lookupSymbolFn)
Internal implementation of lookupSymbolIn that allows for specialized implementations of the lookup f...
static std::optional< SymbolTable::UseRange > getSymbolUsesImpl(FromT from)
The implementation of SymbolTable::getSymbolUses below.
static bool isPotentiallyUnknownSymbolTable(Operation *op)
Return true if the given operation is unknown and may potentially define a symbol table.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
This is an attribute/type replacer that is naively cached.
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
OpListType::iterator iterator
StringAttr getStringAttr(const Twine &bytes)
NamedAttribute getNamedAttr(StringRef name, Attribute val)
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
StringAttr getAttr() const
Returns the name of the held symbol reference as a StringAttr.
InFlightDiagnostic & append(Args &&...args) &
Append arguments to the diagnostic.
Operation * lookupSymbolIn(Operation *symbolTableOp, StringAttr symbol)
Look up a symbol with the specified name within the specified symbol table operation,...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
void push_back(NamedAttribute newAttribute)
Add an attribute with the specified name.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
This class provides the API for ops that are known to be terminators.
A trait used to provide symbol table functionalities to a region operation.
Operation is the basic unit of execution within MLIR.
DictionaryAttr getAttrDictionary()
Return all of the attributes on this operation as a DictionaryAttr.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
AttrClass getAttrOfType(StringAttr name)
Attribute getAttr(StringAttr name)
Return the specified attribute if present, null otherwise.
MLIRContext * getContext()
Return the context this operation is associated with.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Attribute removeAttr(StringAttr name)
Remove the attribute with the specified name if it exists.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
iterator_range< OpIterator > getOps()
Operation * getParentOp()
Return the parent operation this region is attached to.
This class represents a collection of SymbolTables.
Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Operation * lookupSymbolIn(Operation *symbolTableOp, StringAttr symbol)
Look up a symbol with the specified name within the specified symbol table operation,...
SymbolTable & getSymbolTable(Operation *op)
Lookup, or create, a symbol table for an operation.
This class represents a specific symbol use.
This class implements a range of SymbolRef uses.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
static Visibility getSymbolVisibility(Operation *symbol)
Returns the visibility of the given symbol operation.
static StringRef getSymbolAttrName()
Return the name of the attribute used for symbol names.
static void setSymbolVisibility(Operation *symbol, Visibility vis)
Sets the visibility of the given symbol operation.
Operation * getOp() const
Returns the associated operation.
static LogicalResult replaceAllSymbolUses(StringAttr oldSymbol, StringAttr newSymbol, Operation *from)
Attempt to replace all uses of the given symbol 'oldSymbol' with the provided symbol 'newSymbol' that...
Visibility
An enumeration detailing the different visibility types that a symbol may have.
@ Nested
The symbol is visible to the current IR, which may include operations in symbol tables above the one ...
@ Public
The symbol is public and may be referenced anywhere internal or external to the visible references in...
@ Private
The symbol is private and may only be referenced by SymbolRefAttrs local to the operations within the...
static StringRef getVisibilityAttrName()
Return the name of the attribute used for symbol visibility.
LogicalResult rename(StringAttr from, StringAttr to)
Renames the given op or the op refered to by the given name to the given new name and updates the sym...
void erase(Operation *symbol)
Erase the given symbol from the table and delete the operation.
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
Operation * lookup(StringRef name) const
Look up a symbol with the specified name, returning null if no such name exists.
SymbolTable(Operation *symbolTableOp)
Build a symbol table with the symbols within the given operation.
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
static void setSymbolName(Operation *symbol, StringAttr name)
Sets the name of the given symbol operation.
static bool symbolKnownUseEmpty(StringAttr symbol, Operation *from)
Return if the given symbol is known to have no uses that are nested within the given operation 'from'...
FailureOr< StringAttr > renameToUnique(StringAttr from, ArrayRef< SymbolTable * > others)
Renames the given op or the op refered to by the given name to the a name that is unique within this ...
static void walkSymbolTables(Operation *op, bool allSymUsesVisible, function_ref< void(Operation *, bool)> callback)
Walks all symbol table operations nested within, and including, op.
static StringAttr getSymbolName(Operation *symbol)
Returns the name of the given symbol operation, aborting if no symbol is present.
static std::optional< UseRange > getSymbolUses(Operation *from)
Get an iterator range for all of the uses, for any symbol, that are nested within the given operation...
StringAttr insert(Operation *symbol, Block::iterator insertPt={})
Insert a new symbol into the table, and rename it as necessary to avoid collisions.
void remove(Operation *op)
Remove the given symbol from the table, without deleting it.
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
void replaceAllUsesWith(Operation *symbol, StringAttr newSymbolName)
Replace all of the uses of the given symbol with newSymbolName.
SymbolUserMap(SymbolTableCollection &symbolTable, Operation *symbolTableOp)
Build a user map for all of the symbols defined in regions nested under 'symbolTableOp'.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
static WalkResult interrupt()
void addReplacement(ReplaceFn< Attribute > fn)
Register a replacement function for mapping a given attribute or type.
void replaceElementsIn(Operation *op, bool replaceAttrs=true, bool replaceLocs=false, bool replaceTypes=false)
Replace the elements within the given operation.
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
LogicalResult verifySymbol(Operation *op)
LogicalResult verifySymbolTable(Operation *op)
ParseResult parseOptionalVisibilityKeyword(OpAsmParser &parser, NamedAttrList &attrs)
Parse an optional visibility attribute keyword (i.e., public, private, or nested) without quotes in a...
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)