Skip to content

Commit f849866

Browse files
authored
[MLIR] Reduce complexity of searching circular function calls in bufferization (#142099)
The current algorithm searching for circular function calls scales quadratically due to the linear scan of the functions vector that is performed for each element of the vector itself. The PR replaces such algorithm with an O(V + E) version based on the Khan's algorithm for topological sorting, where V is the number of functions and E is the number of function calls.
1 parent 4d4b7cc commit f849866

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

mlir/lib/Dialect/Bufferization/Transforms/OneShotModuleBufferize.cpp

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -341,15 +341,25 @@ static LogicalResult getFuncOpsOrderedByCalls(
341341

342342
// Iteratively remove function operations that do not call any of the
343343
// functions remaining in the callCounter map and add them to ordered list.
344-
while (!numberCallOpsContainedInFuncOp.empty()) {
345-
auto it = llvm::find_if(numberCallOpsContainedInFuncOp,
346-
[](auto entry) { return entry.getSecond() == 0; });
347-
if (it == numberCallOpsContainedInFuncOp.end())
348-
break;
349-
orderedFuncOps.push_back(it->getFirst());
350-
for (auto callee : calledBy[it->getFirst()])
351-
numberCallOpsContainedInFuncOp[callee]--;
352-
numberCallOpsContainedInFuncOp.erase(it);
344+
SmallVector<func::FuncOp> worklist;
345+
346+
for (const auto &entry : numberCallOpsContainedInFuncOp) {
347+
if (entry.second == 0)
348+
worklist.push_back(entry.first);
349+
}
350+
351+
while (!worklist.empty()) {
352+
func::FuncOp func = worklist.pop_back_val();
353+
orderedFuncOps.push_back(func);
354+
355+
for (func::FuncOp caller : calledBy[func]) {
356+
auto &count = numberCallOpsContainedInFuncOp[caller];
357+
358+
if (--count == 0)
359+
worklist.push_back(caller);
360+
}
361+
362+
numberCallOpsContainedInFuncOp.erase(func);
353363
}
354364

355365
// Put all other functions in the list of remaining functions. These are

0 commit comments

Comments
 (0)