llvm-profdata.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // llvm-profdata merges .profdata files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/SmallSet.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/IR/LLVMContext.h"
  17. #include "llvm/ProfileData/InstrProfReader.h"
  18. #include "llvm/ProfileData/InstrProfWriter.h"
  19. #include "llvm/ProfileData/ProfileCommon.h"
  20. #include "llvm/ProfileData/SampleProfReader.h"
  21. #include "llvm/ProfileData/SampleProfWriter.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/Errc.h"
  24. #include "llvm/Support/FileSystem.h"
  25. #include "llvm/Support/Format.h"
  26. #include "llvm/Support/ManagedStatic.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/PrettyStackTrace.h"
  30. #include "llvm/Support/Signals.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. enum ProfileFormat { PF_None = 0, PF_Text, PF_Binary, PF_GCC };
  35. static void exitWithError(const Twine &Message, StringRef Whence = "",
  36. StringRef Hint = "") {
  37. errs() << "error: ";
  38. if (!Whence.empty())
  39. errs() << Whence << ": ";
  40. errs() << Message << "\n";
  41. if (!Hint.empty())
  42. errs() << Hint << "\n";
  43. ::exit(1);
  44. }
  45. static void exitWithError(Error E, StringRef Whence = "") {
  46. if (E.isA<InstrProfError>()) {
  47. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  48. instrprof_error instrError = IPE.get();
  49. StringRef Hint = "";
  50. if (instrError == instrprof_error::unrecognized_format) {
  51. // Hint for common error of forgetting -sample for sample profiles.
  52. Hint = "Perhaps you forgot to use the -sample option?";
  53. }
  54. exitWithError(IPE.message(), Whence, Hint);
  55. });
  56. }
  57. exitWithError(toString(std::move(E)), Whence);
  58. }
  59. static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
  60. exitWithError(EC.message(), Whence);
  61. }
  62. namespace {
  63. enum ProfileKinds { instr, sample };
  64. }
  65. static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
  66. StringRef WhenceFunction = "",
  67. bool ShowHint = true) {
  68. if (!WhenceFile.empty())
  69. errs() << WhenceFile << ": ";
  70. if (!WhenceFunction.empty())
  71. errs() << WhenceFunction << ": ";
  72. auto IPE = instrprof_error::success;
  73. E = handleErrors(std::move(E),
  74. [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
  75. IPE = E->get();
  76. return Error(std::move(E));
  77. });
  78. errs() << toString(std::move(E)) << "\n";
  79. if (ShowHint) {
  80. StringRef Hint = "";
  81. if (IPE != instrprof_error::success) {
  82. switch (IPE) {
  83. case instrprof_error::hash_mismatch:
  84. case instrprof_error::count_mismatch:
  85. case instrprof_error::value_site_count_mismatch:
  86. Hint = "Make sure that all profile data to be merged is generated "
  87. "from the same binary.";
  88. break;
  89. default:
  90. break;
  91. }
  92. }
  93. if (!Hint.empty())
  94. errs() << Hint << "\n";
  95. }
  96. }
  97. struct WeightedFile {
  98. StringRef Filename;
  99. uint64_t Weight;
  100. WeightedFile() {}
  101. WeightedFile(StringRef F, uint64_t W) : Filename{F}, Weight{W} {}
  102. };
  103. typedef SmallVector<WeightedFile, 5> WeightedFileVector;
  104. static void mergeInstrProfile(const WeightedFileVector &Inputs,
  105. StringRef OutputFilename,
  106. ProfileFormat OutputFormat, bool OutputSparse) {
  107. if (OutputFilename.compare("-") == 0)
  108. exitWithError("Cannot write indexed profdata format to stdout.");
  109. if (OutputFormat != PF_Binary && OutputFormat != PF_Text)
  110. exitWithError("Unknown format is specified.");
  111. std::error_code EC;
  112. raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
  113. if (EC)
  114. exitWithErrorCode(EC, OutputFilename);
  115. InstrProfWriter Writer(OutputSparse);
  116. SmallSet<instrprof_error, 4> WriterErrorCodes;
  117. for (const auto &Input : Inputs) {
  118. auto ReaderOrErr = InstrProfReader::create(Input.Filename);
  119. if (Error E = ReaderOrErr.takeError())
  120. exitWithError(std::move(E), Input.Filename);
  121. auto Reader = std::move(ReaderOrErr.get());
  122. bool IsIRProfile = Reader->isIRLevelProfile();
  123. if (Writer.setIsIRLevelProfile(IsIRProfile))
  124. exitWithError("Merge IR generated profile with Clang generated profile.");
  125. for (auto &I : *Reader) {
  126. if (Error E = Writer.addRecord(std::move(I), Input.Weight)) {
  127. // Only show hint the first time an error occurs.
  128. instrprof_error IPE = InstrProfError::take(std::move(E));
  129. bool firstTime = WriterErrorCodes.insert(IPE).second;
  130. handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
  131. I.Name, firstTime);
  132. }
  133. }
  134. if (Reader->hasError())
  135. exitWithError(Reader->getError(), Input.Filename);
  136. }
  137. if (OutputFormat == PF_Text)
  138. Writer.writeText(Output);
  139. else
  140. Writer.write(Output);
  141. }
  142. static sampleprof::SampleProfileFormat FormatMap[] = {
  143. sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Binary,
  144. sampleprof::SPF_GCC};
  145. static void mergeSampleProfile(const WeightedFileVector &Inputs,
  146. StringRef OutputFilename,
  147. ProfileFormat OutputFormat) {
  148. using namespace sampleprof;
  149. auto WriterOrErr =
  150. SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
  151. if (std::error_code EC = WriterOrErr.getError())
  152. exitWithErrorCode(EC, OutputFilename);
  153. auto Writer = std::move(WriterOrErr.get());
  154. StringMap<FunctionSamples> ProfileMap;
  155. SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
  156. LLVMContext Context;
  157. for (const auto &Input : Inputs) {
  158. auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
  159. if (std::error_code EC = ReaderOrErr.getError())
  160. exitWithErrorCode(EC, Input.Filename);
  161. // We need to keep the readers around until after all the files are
  162. // read so that we do not lose the function names stored in each
  163. // reader's memory. The function names are needed to write out the
  164. // merged profile map.
  165. Readers.push_back(std::move(ReaderOrErr.get()));
  166. const auto Reader = Readers.back().get();
  167. if (std::error_code EC = Reader->read())
  168. exitWithErrorCode(EC, Input.Filename);
  169. StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
  170. for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
  171. E = Profiles.end();
  172. I != E; ++I) {
  173. StringRef FName = I->first();
  174. FunctionSamples &Samples = I->second;
  175. sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
  176. if (Result != sampleprof_error::success) {
  177. std::error_code EC = make_error_code(Result);
  178. handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
  179. }
  180. }
  181. }
  182. Writer->write(ProfileMap);
  183. }
  184. static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
  185. StringRef WeightStr, FileName;
  186. std::tie(WeightStr, FileName) = WeightedFilename.split(',');
  187. uint64_t Weight;
  188. if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
  189. exitWithError("Input weight must be a positive integer.");
  190. if (!sys::fs::exists(FileName))
  191. exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
  192. FileName);
  193. return WeightedFile(FileName, Weight);
  194. }
  195. static int merge_main(int argc, const char *argv[]) {
  196. cl::list<std::string> InputFilenames(cl::Positional,
  197. cl::desc("<filename...>"));
  198. cl::list<std::string> WeightedInputFilenames("weighted-input",
  199. cl::desc("<weight>,<filename>"));
  200. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  201. cl::init("-"), cl::Required,
  202. cl::desc("Output file"));
  203. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  204. cl::aliasopt(OutputFilename));
  205. cl::opt<ProfileKinds> ProfileKind(
  206. cl::desc("Profile kind:"), cl::init(instr),
  207. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  208. clEnumVal(sample, "Sample profile"), clEnumValEnd));
  209. cl::opt<ProfileFormat> OutputFormat(
  210. cl::desc("Format of output profile"), cl::init(PF_Binary),
  211. cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
  212. clEnumValN(PF_Text, "text", "Text encoding"),
  213. clEnumValN(PF_GCC, "gcc",
  214. "GCC encoding (only meaningful for -sample)"),
  215. clEnumValEnd));
  216. cl::opt<bool> OutputSparse("sparse", cl::init(false),
  217. cl::desc("Generate a sparse profile (only meaningful for -instr)"));
  218. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
  219. if (InputFilenames.empty() && WeightedInputFilenames.empty())
  220. exitWithError("No input files specified. See " +
  221. sys::path::filename(argv[0]) + " -help");
  222. WeightedFileVector WeightedInputs;
  223. for (StringRef Filename : InputFilenames)
  224. WeightedInputs.push_back(WeightedFile(Filename, 1));
  225. for (StringRef WeightedFilename : WeightedInputFilenames)
  226. WeightedInputs.push_back(parseWeightedFile(WeightedFilename));
  227. if (ProfileKind == instr)
  228. mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
  229. OutputSparse);
  230. else
  231. mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
  232. return 0;
  233. }
  234. static int showInstrProfile(std::string Filename, bool ShowCounts,
  235. bool ShowIndirectCallTargets,
  236. bool ShowDetailedSummary,
  237. std::vector<uint32_t> DetailedSummaryCutoffs,
  238. bool ShowAllFunctions, std::string ShowFunction,
  239. bool TextFormat, raw_fd_ostream &OS) {
  240. auto ReaderOrErr = InstrProfReader::create(Filename);
  241. std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs);
  242. if (ShowDetailedSummary && DetailedSummaryCutoffs.empty()) {
  243. Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
  244. }
  245. InstrProfSummaryBuilder Builder(Cutoffs);
  246. if (Error E = ReaderOrErr.takeError())
  247. exitWithError(std::move(E), Filename);
  248. auto Reader = std::move(ReaderOrErr.get());
  249. bool IsIRInstr = Reader->isIRLevelProfile();
  250. size_t ShownFunctions = 0;
  251. for (const auto &Func : *Reader) {
  252. bool Show =
  253. ShowAllFunctions || (!ShowFunction.empty() &&
  254. Func.Name.find(ShowFunction) != Func.Name.npos);
  255. bool doTextFormatDump = (Show && ShowCounts && TextFormat);
  256. if (doTextFormatDump) {
  257. InstrProfSymtab &Symtab = Reader->getSymtab();
  258. InstrProfWriter::writeRecordInText(Func, Symtab, OS);
  259. continue;
  260. }
  261. assert(Func.Counts.size() > 0 && "function missing entry counter");
  262. Builder.addRecord(Func);
  263. if (Show) {
  264. if (!ShownFunctions)
  265. OS << "Counters:\n";
  266. ++ShownFunctions;
  267. OS << " " << Func.Name << ":\n"
  268. << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
  269. << " Counters: " << Func.Counts.size() << "\n";
  270. if (!IsIRInstr)
  271. OS << " Function count: " << Func.Counts[0] << "\n";
  272. if (ShowIndirectCallTargets)
  273. OS << " Indirect Call Site Count: "
  274. << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
  275. if (ShowCounts) {
  276. OS << " Block counts: [";
  277. size_t Start = (IsIRInstr ? 0 : 1);
  278. for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
  279. OS << (I == Start ? "" : ", ") << Func.Counts[I];
  280. }
  281. OS << "]\n";
  282. }
  283. if (ShowIndirectCallTargets) {
  284. InstrProfSymtab &Symtab = Reader->getSymtab();
  285. uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
  286. OS << " Indirect Target Results: \n";
  287. for (size_t I = 0; I < NS; ++I) {
  288. uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
  289. std::unique_ptr<InstrProfValueData[]> VD =
  290. Func.getValueForSite(IPVK_IndirectCallTarget, I);
  291. for (uint32_t V = 0; V < NV; V++) {
  292. OS << "\t[ " << I << ", ";
  293. OS << Symtab.getFuncName(VD[V].Value) << ", " << VD[V].Count
  294. << " ]\n";
  295. }
  296. }
  297. }
  298. }
  299. }
  300. if (Reader->hasError())
  301. exitWithError(Reader->getError(), Filename);
  302. if (ShowCounts && TextFormat)
  303. return 0;
  304. std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
  305. if (ShowAllFunctions || !ShowFunction.empty())
  306. OS << "Functions shown: " << ShownFunctions << "\n";
  307. OS << "Total functions: " << PS->getNumFunctions() << "\n";
  308. OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
  309. OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
  310. if (ShowDetailedSummary) {
  311. OS << "Detailed summary:\n";
  312. OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
  313. OS << "Total count: " << PS->getTotalCount() << "\n";
  314. for (auto Entry : PS->getDetailedSummary()) {
  315. OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
  316. << " account for "
  317. << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
  318. << " percentage of the total counts.\n";
  319. }
  320. }
  321. return 0;
  322. }
  323. static int showSampleProfile(std::string Filename, bool ShowCounts,
  324. bool ShowAllFunctions, std::string ShowFunction,
  325. raw_fd_ostream &OS) {
  326. using namespace sampleprof;
  327. LLVMContext Context;
  328. auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
  329. if (std::error_code EC = ReaderOrErr.getError())
  330. exitWithErrorCode(EC, Filename);
  331. auto Reader = std::move(ReaderOrErr.get());
  332. if (std::error_code EC = Reader->read())
  333. exitWithErrorCode(EC, Filename);
  334. if (ShowAllFunctions || ShowFunction.empty())
  335. Reader->dump(OS);
  336. else
  337. Reader->dumpFunctionProfile(ShowFunction, OS);
  338. return 0;
  339. }
  340. static int show_main(int argc, const char *argv[]) {
  341. cl::opt<std::string> Filename(cl::Positional, cl::Required,
  342. cl::desc("<profdata-file>"));
  343. cl::opt<bool> ShowCounts("counts", cl::init(false),
  344. cl::desc("Show counter values for shown functions"));
  345. cl::opt<bool> TextFormat(
  346. "text", cl::init(false),
  347. cl::desc("Show instr profile data in text dump format"));
  348. cl::opt<bool> ShowIndirectCallTargets(
  349. "ic-targets", cl::init(false),
  350. cl::desc("Show indirect call site target values for shown functions"));
  351. cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
  352. cl::desc("Show detailed profile summary"));
  353. cl::list<uint32_t> DetailedSummaryCutoffs(
  354. cl::CommaSeparated, "detailed-summary-cutoffs",
  355. cl::desc(
  356. "Cutoff percentages (times 10000) for generating detailed summary"),
  357. cl::value_desc("800000,901000,999999"));
  358. cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
  359. cl::desc("Details for every function"));
  360. cl::opt<std::string> ShowFunction("function",
  361. cl::desc("Details for matching functions"));
  362. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  363. cl::init("-"), cl::desc("Output file"));
  364. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  365. cl::aliasopt(OutputFilename));
  366. cl::opt<ProfileKinds> ProfileKind(
  367. cl::desc("Profile kind:"), cl::init(instr),
  368. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  369. clEnumVal(sample, "Sample profile"), clEnumValEnd));
  370. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
  371. if (OutputFilename.empty())
  372. OutputFilename = "-";
  373. std::error_code EC;
  374. raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
  375. if (EC)
  376. exitWithErrorCode(EC, OutputFilename);
  377. if (ShowAllFunctions && !ShowFunction.empty())
  378. errs() << "warning: -function argument ignored: showing all functions\n";
  379. std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
  380. DetailedSummaryCutoffs.end());
  381. if (ProfileKind == instr)
  382. return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
  383. ShowDetailedSummary, DetailedSummaryCutoffs,
  384. ShowAllFunctions, ShowFunction, TextFormat, OS);
  385. else
  386. return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
  387. ShowFunction, OS);
  388. }
  389. int main(int argc, const char *argv[]) {
  390. // Print a stack trace if we signal out.
  391. sys::PrintStackTraceOnErrorSignal();
  392. PrettyStackTraceProgram X(argc, argv);
  393. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  394. StringRef ProgName(sys::path::filename(argv[0]));
  395. if (argc > 1) {
  396. int (*func)(int, const char *[]) = nullptr;
  397. if (strcmp(argv[1], "merge") == 0)
  398. func = merge_main;
  399. else if (strcmp(argv[1], "show") == 0)
  400. func = show_main;
  401. if (func) {
  402. std::string Invocation(ProgName.str() + " " + argv[1]);
  403. argv[1] = Invocation.c_str();
  404. return func(argc - 1, argv + 1);
  405. }
  406. if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
  407. strcmp(argv[1], "--help") == 0) {
  408. errs() << "OVERVIEW: LLVM profile data tools\n\n"
  409. << "USAGE: " << ProgName << " <command> [args...]\n"
  410. << "USAGE: " << ProgName << " <command> -help\n\n"
  411. << "Available commands: merge, show\n";
  412. return 0;
  413. }
  414. }
  415. if (argc < 2)
  416. errs() << ProgName << ": No command specified!\n";
  417. else
  418. errs() << ProgName << ": Unknown command!\n";
  419. errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
  420. return 1;
  421. }