OptReport.cpp 16 KB

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