1 //===- OpStats.cpp - Prints stats of operations in module -----------------===// 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/Module.h" 10 #include "mlir/IR/Operation.h" 11 #include "mlir/IR/OperationSupport.h" 12 #include "mlir/Pass/Pass.h" 13 #include "llvm/ADT/DenseMap.h" 14 #include "llvm/Support/Format.h" 15 #include "llvm/Support/raw_ostream.h" 16 17 using namespace mlir; 18 19 namespace { 20 struct PrintOpStatsPass : public ModulePass<PrintOpStatsPass> { 21 explicit PrintOpStatsPass(raw_ostream &os = llvm::errs()) : os(os) {} 22 23 // Prints the resultant operation statistics post iterating over the module. 24 void runOnModule() override; 25 26 // Print summary of op stats. 27 void printSummary(); 28 29 private: 30 llvm::StringMap<int64_t> opCount; 31 raw_ostream &os; 32 }; 33 } // namespace 34 35 void PrintOpStatsPass::runOnModule() { 36 opCount.clear(); 37 38 // Compute the operation statistics for each function in the module. 39 for (auto &op : getModule()) 40 op.walk([&](Operation *op) { ++opCount[op->getName().getStringRef()]; }); 41 printSummary(); 42 } 43 44 void PrintOpStatsPass::printSummary() { 45 os << "Operations encountered:\n"; 46 os << "-----------------------\n"; 47 SmallVector<StringRef, 64> sorted(opCount.keys()); 48 llvm::sort(sorted); 49 50 // Split an operation name from its dialect prefix. 51 auto splitOperationName = [](StringRef opName) { 52 auto splitName = opName.split('.'); 53 return splitName.second.empty() ? std::make_pair("", splitName.first) 54 : splitName; 55 }; 56 57 // Compute the largest dialect and operation name. 58 StringRef dialectName, opName; 59 size_t maxLenOpName = 0, maxLenDialect = 0; 60 for (const auto &key : sorted) { 61 std::tie(dialectName, opName) = splitOperationName(key); 62 maxLenDialect = std::max(maxLenDialect, dialectName.size()); 63 maxLenOpName = std::max(maxLenOpName, opName.size()); 64 } 65 66 for (const auto &key : sorted) { 67 std::tie(dialectName, opName) = splitOperationName(key); 68 69 // Left-align the names (aligning on the dialect) and right-align the count 70 // below. The alignment is for readability and does not affect CSV/FileCheck 71 // parsing. 72 if (dialectName.empty()) 73 os.indent(maxLenDialect + 3); 74 else 75 os << llvm::right_justify(dialectName, maxLenDialect + 2) << '.'; 76 77 // Left justify the operation name. 78 os << llvm::left_justify(opName, maxLenOpName) << " , " << opCount[key] 79 << '\n'; 80 } 81 } 82 83 static PassRegistration<PrintOpStatsPass> 84 pass("print-op-stats", "Print statistics of operations"); 85