1//===------------------ llvm-opt-report/OptReport.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/// \file
10/// This file implements a tool that can parse the YAML optimization
11/// records and generate an optimization summary annotated source listing
12/// report.
13///
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Demangle/Demangle.h"
18#include "llvm/Remarks/Remark.h"
19#include "llvm/Remarks/RemarkFormat.h"
20#include "llvm/Remarks/RemarkParser.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Error.h"
23#include "llvm/Support/ErrorOr.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Format.h"
26#include "llvm/Support/InitLLVM.h"
27#include "llvm/Support/LineIterator.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/Path.h"
30#include "llvm/Support/TypeSize.h"
31#include "llvm/Support/WithColor.h"
32#include "llvm/Support/raw_ostream.h"
33#include <cstdlib>
34#include <map>
35#include <optional>
36#include <set>
37
38using namespace llvm;
39
40// Mark all our options with this category, everything else (except for -version
41// and -help) will be hidden.
42static cl::OptionCategory
43 OptReportCategory("llvm-opt-report options");
44
45static cl::opt<std::string>
46 InputFileName(cl::Positional, cl::desc("<input>"), cl::init(Val: "-"),
47 cl::cat(OptReportCategory));
48
49static cl::opt<std::string>
50 OutputFileName("o", cl::desc("Output file"), cl::init(Val: "-"),
51 cl::cat(OptReportCategory));
52
53static cl::opt<std::string>
54 InputRelDir("r", cl::desc("Root for relative input paths"), cl::init(Val: ""),
55 cl::cat(OptReportCategory));
56
57static cl::opt<bool>
58 Succinct("s", cl::desc("Don't include vectorization factors, etc."),
59 cl::init(Val: false), cl::cat(OptReportCategory));
60
61static cl::opt<bool>
62 NoDemangle("no-demangle", cl::desc("Don't demangle function names"),
63 cl::init(Val: false), cl::cat(OptReportCategory));
64
65static cl::opt<std::string> ParserFormat("format",
66 cl::desc("The format of the remarks."),
67 cl::init(Val: "yaml"),
68 cl::cat(OptReportCategory));
69
70namespace {
71// For each location in the source file, the common per-transformation state
72// collected.
73struct OptReportLocationItemInfo {
74 bool Analyzed = false;
75 bool Transformed = false;
76
77 OptReportLocationItemInfo &operator |= (
78 const OptReportLocationItemInfo &RHS) {
79 Analyzed |= RHS.Analyzed;
80 Transformed |= RHS.Transformed;
81
82 return *this;
83 }
84
85 bool operator < (const OptReportLocationItemInfo &RHS) const {
86 if (Analyzed < RHS.Analyzed)
87 return true;
88 else if (Analyzed > RHS.Analyzed)
89 return false;
90 else if (Transformed < RHS.Transformed)
91 return true;
92 return false;
93 }
94};
95
96// The per-location information collected for producing an optimization report.
97struct OptReportLocationInfo {
98 OptReportLocationItemInfo Inlined;
99 OptReportLocationItemInfo Unrolled;
100 OptReportLocationItemInfo Vectorized;
101
102 ElementCount VectorizationFactor = ElementCount::getFixed(MinVal: 1);
103 int InterleaveCount = 1;
104 int UnrollCount = 1;
105
106 OptReportLocationInfo &operator |= (const OptReportLocationInfo &RHS) {
107 Inlined |= RHS.Inlined;
108 Unrolled |= RHS.Unrolled;
109 Vectorized |= RHS.Vectorized;
110
111 if (ElementCount::isKnownLT(LHS: VectorizationFactor, RHS: RHS.VectorizationFactor))
112 VectorizationFactor = RHS.VectorizationFactor;
113
114 InterleaveCount = std::max(a: InterleaveCount, b: RHS.InterleaveCount);
115 UnrollCount = std::max(a: UnrollCount, b: RHS.UnrollCount);
116
117 return *this;
118 }
119
120 bool operator < (const OptReportLocationInfo &RHS) const {
121 if (Inlined < RHS.Inlined)
122 return true;
123 else if (RHS.Inlined < Inlined)
124 return false;
125 else if (Unrolled < RHS.Unrolled)
126 return true;
127 else if (RHS.Unrolled < Unrolled)
128 return false;
129 else if (Vectorized < RHS.Vectorized)
130 return true;
131 else if (RHS.Vectorized < Vectorized || Succinct)
132 return false;
133 else if (ElementCount::isKnownLT(LHS: VectorizationFactor,
134 RHS: RHS.VectorizationFactor))
135 return true;
136 else if (ElementCount::isKnownGT(LHS: VectorizationFactor,
137 RHS: RHS.VectorizationFactor))
138 return false;
139 else if (InterleaveCount < RHS.InterleaveCount)
140 return true;
141 else if (InterleaveCount > RHS.InterleaveCount)
142 return false;
143 else if (UnrollCount < RHS.UnrollCount)
144 return true;
145 return false;
146 }
147};
148
149typedef std::map<std::string, std::map<int, std::map<std::string, std::map<int,
150 OptReportLocationInfo>>>> LocationInfoTy;
151} // anonymous namespace
152
153static bool readLocationInfo(LocationInfoTy &LocationInfo) {
154 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
155 MemoryBuffer::getFile(Filename: InputFileName.c_str());
156 if (std::error_code EC = Buf.getError()) {
157 WithColor::error() << "Can't open file " << InputFileName << ": "
158 << EC.message() << "\n";
159 return false;
160 }
161
162 Expected<remarks::Format> Format = remarks::parseFormat(FormatStr: ParserFormat);
163 if (!Format) {
164 handleAllErrors(E: Format.takeError(), Handlers: [&](const ErrorInfoBase &PE) {
165 PE.log(OS&: WithColor::error());
166 errs() << '\n';
167 });
168 return false;
169 }
170
171 Expected<std::unique_ptr<remarks::RemarkParser>> MaybeParser =
172 remarks::createRemarkParserFromMeta(ParserFormat: *Format, Buf: (*Buf)->getBuffer());
173 if (!MaybeParser) {
174 handleAllErrors(E: MaybeParser.takeError(), Handlers: [&](const ErrorInfoBase &PE) {
175 PE.log(OS&: WithColor::error());
176 errs() << '\n';
177 });
178 return false;
179 }
180 remarks::RemarkParser &Parser = **MaybeParser;
181
182 while (true) {
183 Expected<std::unique_ptr<remarks::Remark>> MaybeRemark = Parser.next();
184 if (!MaybeRemark) {
185 Error E = MaybeRemark.takeError();
186 if (E.isA<remarks::EndOfFileError>()) {
187 // EOF.
188 consumeError(Err: std::move(E));
189 break;
190 }
191 handleAllErrors(E: std::move(E), Handlers: [&](const ErrorInfoBase &PE) {
192 PE.log(OS&: WithColor::error());
193 errs() << '\n';
194 });
195 return false;
196 }
197
198 const remarks::Remark &Remark = **MaybeRemark;
199
200 bool Transformed = Remark.RemarkType == remarks::Type::Passed;
201
202 ElementCount VectorizationFactor = ElementCount::getFixed(MinVal: 1);
203 int InterleaveCount = 1;
204 int UnrollCount = 1;
205
206 for (const remarks::Argument &Arg : Remark.Args) {
207 if (Arg.Key == "VectorizationFactor") {
208 int MinValue = 1;
209 bool IsScalable = false;
210 if (Arg.Val.starts_with(Prefix: "vscale x ")) {
211 Arg.Val.drop_front(N: 9).getAsInteger(Radix: 10, Result&: MinValue);
212 IsScalable = true;
213 } else {
214 Arg.Val.getAsInteger(Radix: 10, Result&: MinValue);
215 }
216 VectorizationFactor = ElementCount::get(MinVal: MinValue, Scalable: IsScalable);
217 } else if (Arg.Key == "InterleaveCount") {
218 Arg.Val.getAsInteger(Radix: 10, Result&: InterleaveCount);
219 } else if (Arg.Key == "UnrollCount") {
220 Arg.Val.getAsInteger(Radix: 10, Result&: UnrollCount);
221 }
222 }
223
224 const std::optional<remarks::RemarkLocation> &Loc = Remark.Loc;
225 if (!Loc)
226 continue;
227
228 StringRef File = Loc->SourceFilePath;
229 unsigned Line = Loc->SourceLine;
230 unsigned Column = Loc->SourceColumn;
231
232 // We track information on both actual and potential transformations. This
233 // way, if there are multiple possible things on a line that are, or could
234 // have been transformed, we can indicate that explicitly in the output.
235 auto UpdateLLII = [Transformed](OptReportLocationItemInfo &LLII) {
236 LLII.Analyzed = true;
237 if (Transformed)
238 LLII.Transformed = true;
239 };
240
241 if (Remark.PassName == "inline") {
242 auto &LI = LocationInfo[std::string(File)][Line]
243 [std::string(Remark.FunctionName)][Column];
244 UpdateLLII(LI.Inlined);
245 } else if (Remark.PassName == "loop-unroll") {
246 auto &LI = LocationInfo[std::string(File)][Line]
247 [std::string(Remark.FunctionName)][Column];
248 LI.UnrollCount = UnrollCount;
249 UpdateLLII(LI.Unrolled);
250 } else if (Remark.PassName == "loop-vectorize") {
251 auto &LI = LocationInfo[std::string(File)][Line]
252 [std::string(Remark.FunctionName)][Column];
253 LI.VectorizationFactor = VectorizationFactor;
254 LI.InterleaveCount = InterleaveCount;
255 UpdateLLII(LI.Vectorized);
256 }
257 }
258
259 return true;
260}
261
262static bool writeReport(LocationInfoTy &LocationInfo) {
263 std::error_code EC;
264 llvm::raw_fd_ostream OS(OutputFileName, EC, llvm::sys::fs::OF_TextWithCRLF);
265 if (EC) {
266 WithColor::error() << "Can't open file " << OutputFileName << ": "
267 << EC.message() << "\n";
268 return false;
269 }
270
271 bool FirstFile = true;
272 for (auto &FI : LocationInfo) {
273 SmallString<128> FileName(FI.first);
274 if (!InputRelDir.empty())
275 sys::path::make_absolute(current_directory: InputRelDir, path&: FileName);
276
277 const auto &FileInfo = FI.second;
278
279 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
280 MemoryBuffer::getFile(Filename: FileName);
281 if (std::error_code EC = Buf.getError()) {
282 WithColor::error() << "Can't open file " << FileName << ": "
283 << EC.message() << "\n";
284 return false;
285 }
286
287 if (FirstFile)
288 FirstFile = false;
289 else
290 OS << "\n";
291
292 OS << "< " << FileName << "\n";
293
294 // Figure out how many characters we need for the vectorization factors
295 // and similar.
296 OptReportLocationInfo MaxLI;
297 for (auto &FLI : FileInfo)
298 for (auto &FI : FLI.second)
299 for (auto &LI : FI.second)
300 MaxLI |= LI.second;
301
302 bool NothingInlined = !MaxLI.Inlined.Transformed;
303 bool NothingUnrolled = !MaxLI.Unrolled.Transformed;
304 bool NothingVectorized = !MaxLI.Vectorized.Transformed;
305
306 unsigned VFDigits =
307 llvm::utostr(X: MaxLI.VectorizationFactor.getKnownMinValue()).size();
308 if (MaxLI.VectorizationFactor.isScalable())
309 VFDigits += 2; // For "Nx..."
310
311 unsigned ICDigits = llvm::utostr(X: MaxLI.InterleaveCount).size();
312 unsigned UCDigits = llvm::utostr(X: MaxLI.UnrollCount).size();
313
314 // Figure out how many characters we need for the line numbers.
315 int64_t NumLines = 0;
316 for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI)
317 ++NumLines;
318
319 unsigned LNDigits = llvm::utostr(X: NumLines).size();
320
321 for (line_iterator LI(*Buf.get(), false); LI != line_iterator(); ++LI) {
322 int64_t L = LI.line_number();
323 auto LII = FileInfo.find(x: L);
324
325 auto PrintLine = [&](bool PrintFuncName,
326 const std::set<std::string> &FuncNameSet) {
327 OptReportLocationInfo LLI;
328
329 std::map<int, OptReportLocationInfo> ColsInfo;
330 unsigned InlinedCols = 0, UnrolledCols = 0, VectorizedCols = 0;
331
332 if (LII != FileInfo.end() && !FuncNameSet.empty()) {
333 const auto &LineInfo = LII->second;
334
335 for (auto &CI : LineInfo.find(x: *FuncNameSet.begin())->second) {
336 int Col = CI.first;
337 ColsInfo[Col] = CI.second;
338 InlinedCols += CI.second.Inlined.Analyzed;
339 UnrolledCols += CI.second.Unrolled.Analyzed;
340 VectorizedCols += CI.second.Vectorized.Analyzed;
341 LLI |= CI.second;
342 }
343 }
344
345 if (PrintFuncName) {
346 OS << " > ";
347
348 bool FirstFunc = true;
349 for (const auto &FuncName : FuncNameSet) {
350 if (FirstFunc)
351 FirstFunc = false;
352 else
353 OS << ", ";
354
355 bool Printed = false;
356 if (!NoDemangle) {
357 if (char *Demangled = itaniumDemangle(mangled_name: FuncName)) {
358 OS << Demangled;
359 Printed = true;
360 std::free(ptr: Demangled);
361 }
362 }
363
364 if (!Printed)
365 OS << FuncName;
366 }
367
368 OS << ":\n";
369 }
370
371 // We try to keep the output as concise as possible. If only one thing on
372 // a given line could have been inlined, vectorized, etc. then we can put
373 // the marker on the source line itself. If there are multiple options
374 // then we want to distinguish them by placing the marker for each
375 // transformation on a separate line following the source line. When we
376 // do this, we use a '^' character to point to the appropriate column in
377 // the source line.
378
379 std::string USpaces(Succinct ? 0 : UCDigits, ' ');
380 std::string VSpaces(Succinct ? 0 : VFDigits + ICDigits + 1, ' ');
381
382 auto UStr = [UCDigits](OptReportLocationInfo &LLI) {
383 std::string R;
384 raw_string_ostream RS(R);
385
386 if (!Succinct) {
387 RS << LLI.UnrollCount;
388 RS << std::string(UCDigits - R.size(), ' ');
389 }
390
391 return R;
392 };
393
394 auto VStr = [VFDigits,
395 ICDigits](OptReportLocationInfo &LLI) -> std::string {
396 std::string R;
397 raw_string_ostream RS(R);
398
399 if (!Succinct) {
400 if (LLI.VectorizationFactor.isScalable())
401 RS << "Nx";
402 RS << LLI.VectorizationFactor.getKnownMinValue() << ","
403 << LLI.InterleaveCount;
404 RS << std::string(VFDigits + ICDigits + 1 - R.size(), ' ');
405 }
406
407 return R;
408 };
409
410 OS << llvm::format_decimal(N: L, Width: LNDigits) << " ";
411 OS << (LLI.Inlined.Transformed && InlinedCols < 2 ? "I" :
412 (NothingInlined ? "" : " "));
413 OS << (LLI.Unrolled.Transformed && UnrolledCols < 2 ?
414 "U" + UStr(LLI) : (NothingUnrolled ? "" : " " + USpaces));
415 OS << (LLI.Vectorized.Transformed && VectorizedCols < 2 ?
416 "V" + VStr(LLI) : (NothingVectorized ? "" : " " + VSpaces));
417
418 OS << " | " << *LI << "\n";
419
420 for (auto &J : ColsInfo) {
421 if ((J.second.Inlined.Transformed && InlinedCols > 1) ||
422 (J.second.Unrolled.Transformed && UnrolledCols > 1) ||
423 (J.second.Vectorized.Transformed && VectorizedCols > 1)) {
424 OS << std::string(LNDigits + 1, ' ');
425 OS << (J.second.Inlined.Transformed &&
426 InlinedCols > 1 ? "I" : (NothingInlined ? "" : " "));
427 OS << (J.second.Unrolled.Transformed &&
428 UnrolledCols > 1 ? "U" + UStr(J.second) :
429 (NothingUnrolled ? "" : " " + USpaces));
430 OS << (J.second.Vectorized.Transformed &&
431 VectorizedCols > 1 ? "V" + VStr(J.second) :
432 (NothingVectorized ? "" : " " + VSpaces));
433
434 OS << " | " << std::string(J.first - 1, ' ') << "^\n";
435 }
436 }
437 };
438
439 // We need to figure out if the optimizations for this line were the same
440 // in each function context. If not, then we want to group the similar
441 // function contexts together and display each group separately. If
442 // they're all the same, then we only display the line once without any
443 // additional markings.
444 std::map<std::map<int, OptReportLocationInfo>,
445 std::set<std::string>> UniqueLIs;
446
447 OptReportLocationInfo AllLI;
448 if (LII != FileInfo.end()) {
449 const auto &FuncLineInfo = LII->second;
450 for (const auto &FLII : FuncLineInfo) {
451 UniqueLIs[FLII.second].insert(x: FLII.first);
452
453 for (const auto &OI : FLII.second)
454 AllLI |= OI.second;
455 }
456 }
457
458 bool NothingHappened = !AllLI.Inlined.Transformed &&
459 !AllLI.Unrolled.Transformed &&
460 !AllLI.Vectorized.Transformed;
461 if (UniqueLIs.size() > 1 && !NothingHappened) {
462 OS << " [[\n";
463 for (const auto &FSLI : UniqueLIs)
464 PrintLine(true, FSLI.second);
465 OS << " ]]\n";
466 } else if (UniqueLIs.size() == 1) {
467 PrintLine(false, UniqueLIs.begin()->second);
468 } else {
469 PrintLine(false, std::set<std::string>());
470 }
471 }
472 }
473
474 return true;
475}
476
477int main(int argc, const char **argv) {
478 InitLLVM X(argc, argv);
479
480 cl::HideUnrelatedOptions(Category&: OptReportCategory);
481 cl::ParseCommandLineOptions(
482 argc, argv,
483 Overview: "A tool to generate an optimization report from YAML optimization"
484 " record files.\n");
485
486 LocationInfoTy LocationInfo;
487 if (!readLocationInfo(LocationInfo))
488 return 1;
489 if (!writeReport(LocationInfo))
490 return 1;
491
492 return 0;
493}
494