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