1//===- RemarkInstructionMix.cpp -------------------------------------------===//
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// Generic tool to extract instruction mix from asm-printer remarks.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RemarkUtilHelpers.h"
14#include "RemarkUtilRegistry.h"
15
16#include "llvm/Support/Format.h"
17#include "llvm/Support/FormattedStream.h"
18#include "llvm/Support/Regex.h"
19
20#include <numeric>
21
22using namespace llvm;
23using namespace remarks;
24using namespace llvm::remarkutil;
25
26namespace instructionmix {
27
28static cl::SubCommand
29 InstructionMix("instruction-mix",
30 "Instruction Mix (requires asm-printer remarks)");
31
32static cl::opt<std::string>
33 FunctionFilter("filter", cl::sub(InstructionMix), cl::ValueOptional,
34 cl::desc("Optional function name to filter collection by"));
35
36static cl::opt<std::string>
37 FunctionFilterRE("rfilter", cl::sub(InstructionMix), cl::ValueOptional,
38 cl::desc("Optional function name to filter collection by "
39 "(accepts regular expressions)"));
40
41enum ReportStyleOptions { human_output, csv_output };
42static cl::opt<ReportStyleOptions> ReportStyle(
43 "report_style", cl::sub(InstructionMix),
44 cl::init(Val: ReportStyleOptions::human_output),
45 cl::desc("Choose the report output format:"),
46 cl::values(clEnumValN(human_output, "human", "Human-readable format"),
47 clEnumValN(csv_output, "csv", "CSV format")));
48
49INPUT_FORMAT_COMMAND_LINE_OPTIONS(InstructionMix)
50INPUT_OUTPUT_COMMAND_LINE_OPTIONS(InstructionMix)
51
52static Error tryInstructionMix() {
53 auto MaybeOF =
54 getOutputFileWithFlags(OutputFileName, Flags: sys::fs::OF_TextWithCRLF);
55 if (!MaybeOF)
56 return MaybeOF.takeError();
57
58 auto OF = std::move(*MaybeOF);
59 auto MaybeBuf = getInputMemoryBuffer(InputFileName);
60 if (!MaybeBuf)
61 return MaybeBuf.takeError();
62 auto MaybeParser = createRemarkParser(ParserFormat: InputFormat, Buf: (*MaybeBuf)->getBuffer());
63 if (!MaybeParser)
64 return MaybeParser.takeError();
65
66 Expected<std::optional<FilterMatcher>> Filter =
67 FilterMatcher::createExactOrRE(ExactArg: FunctionFilter, REArg: FunctionFilterRE);
68 if (!Filter)
69 return Filter.takeError();
70
71 // Collect the histogram of instruction counts.
72 llvm::DenseMap<StringRef, unsigned> Histogram;
73 auto &Parser = **MaybeParser;
74 auto MaybeRemark = Parser.next();
75 for (; MaybeRemark; MaybeRemark = Parser.next()) {
76 Remark &Remark = **MaybeRemark;
77 if (Remark.RemarkName != "InstructionMix")
78 continue;
79 if (*Filter && !(*Filter)->match(StringToMatch: Remark.FunctionName))
80 continue;
81 for (auto &Arg : Remark.Args) {
82 StringRef Key = Arg.Key;
83 if (!Key.consume_front(Prefix: "INST_"))
84 continue;
85 unsigned Val = 0;
86 bool ParseError = Arg.Val.getAsInteger(Radix: 10, Result&: Val);
87 assert(!ParseError);
88 (void)ParseError;
89 Histogram[Key] += Val;
90 }
91 }
92
93 // Sort it.
94 using MixEntry = std::pair<StringRef, unsigned>;
95 llvm::SmallVector<MixEntry> Mix(Histogram.begin(), Histogram.end());
96 std::sort(first: Mix.begin(), last: Mix.end(), comp: [](const auto &LHS, const auto &RHS) {
97 return LHS.second > RHS.second;
98 });
99
100 // Print the results.
101 switch (ReportStyle) {
102 case human_output: {
103 formatted_raw_ostream FOS(OF->os());
104 size_t MaxMnemonic =
105 std::accumulate(first: Mix.begin(), last: Mix.end(), init: StringRef("Instruction").size(),
106 binary_op: [](size_t MaxMnemonic, const MixEntry &Elt) {
107 return std::max(a: MaxMnemonic, b: Elt.first.size());
108 });
109 unsigned MaxValue = std::accumulate(
110 first: Mix.begin(), last: Mix.end(), init: 1, binary_op: [](unsigned MaxValue, const MixEntry &Elt) {
111 return std::max(a: MaxValue, b: Elt.second);
112 });
113 unsigned ValueWidth = NumDigitsBase10(X: MaxValue);
114 FOS << "Instruction";
115 FOS.PadToColumn(NewCol: MaxMnemonic + 1) << "Count\n";
116 FOS << "-----------";
117 FOS.PadToColumn(NewCol: MaxMnemonic + 1) << "-----\n";
118 for (const auto &[Inst, Count] : Mix) {
119 FOS << Inst;
120 FOS.PadToColumn(NewCol: MaxMnemonic + 1)
121 << " " << format_decimal(N: Count, Width: ValueWidth) << "\n";
122 }
123 } break;
124 case csv_output: {
125 OF->os() << "Instruction,Count\n";
126 for (const auto &[Inst, Count] : Mix)
127 OF->os() << Inst << "," << Count << "\n";
128 } break;
129 }
130
131 auto E = MaybeRemark.takeError();
132 if (!E.isA<EndOfFileError>())
133 return E;
134 consumeError(Err: std::move(E));
135 OF->keep();
136 return Error::success();
137}
138
139static CommandRegistration InstructionMixReg(&InstructionMix,
140 tryInstructionMix);
141
142} // namespace instructionmix
143