llvm-profdata.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
  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. // llvm-profdata merges .profdata files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/SmallSet.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/IR/LLVMContext.h"
  16. #include "llvm/ProfileData/InstrProfReader.h"
  17. #include "llvm/ProfileData/InstrProfWriter.h"
  18. #include "llvm/ProfileData/ProfileCommon.h"
  19. #include "llvm/ProfileData/SampleProfReader.h"
  20. #include "llvm/ProfileData/SampleProfWriter.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/Errc.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/Format.h"
  25. #include "llvm/Support/InitLLVM.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/ThreadPool.h"
  29. #include "llvm/Support/WithColor.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. using namespace llvm;
  33. enum ProfileFormat {
  34. PF_None = 0,
  35. PF_Text,
  36. PF_Compact_Binary,
  37. PF_GCC,
  38. PF_Binary
  39. };
  40. static void warn(Twine Message, std::string Whence = "",
  41. std::string Hint = "") {
  42. WithColor::warning();
  43. if (!Whence.empty())
  44. errs() << Whence << ": ";
  45. errs() << Message << "\n";
  46. if (!Hint.empty())
  47. WithColor::note() << Hint << "\n";
  48. }
  49. static void exitWithError(Twine Message, std::string Whence = "",
  50. std::string Hint = "") {
  51. WithColor::error();
  52. if (!Whence.empty())
  53. errs() << Whence << ": ";
  54. errs() << Message << "\n";
  55. if (!Hint.empty())
  56. WithColor::note() << Hint << "\n";
  57. ::exit(1);
  58. }
  59. static void exitWithError(Error E, StringRef Whence = "") {
  60. if (E.isA<InstrProfError>()) {
  61. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  62. instrprof_error instrError = IPE.get();
  63. StringRef Hint = "";
  64. if (instrError == instrprof_error::unrecognized_format) {
  65. // Hint for common error of forgetting -sample for sample profiles.
  66. Hint = "Perhaps you forgot to use the -sample option?";
  67. }
  68. exitWithError(IPE.message(), Whence, Hint);
  69. });
  70. }
  71. exitWithError(toString(std::move(E)), Whence);
  72. }
  73. static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
  74. exitWithError(EC.message(), Whence);
  75. }
  76. namespace {
  77. enum ProfileKinds { instr, sample };
  78. }
  79. static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
  80. StringRef WhenceFunction = "",
  81. bool ShowHint = true) {
  82. if (!WhenceFile.empty())
  83. errs() << WhenceFile << ": ";
  84. if (!WhenceFunction.empty())
  85. errs() << WhenceFunction << ": ";
  86. auto IPE = instrprof_error::success;
  87. E = handleErrors(std::move(E),
  88. [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
  89. IPE = E->get();
  90. return Error(std::move(E));
  91. });
  92. errs() << toString(std::move(E)) << "\n";
  93. if (ShowHint) {
  94. StringRef Hint = "";
  95. if (IPE != instrprof_error::success) {
  96. switch (IPE) {
  97. case instrprof_error::hash_mismatch:
  98. case instrprof_error::count_mismatch:
  99. case instrprof_error::value_site_count_mismatch:
  100. Hint = "Make sure that all profile data to be merged is generated "
  101. "from the same binary.";
  102. break;
  103. default:
  104. break;
  105. }
  106. }
  107. if (!Hint.empty())
  108. errs() << Hint << "\n";
  109. }
  110. }
  111. namespace {
  112. /// A remapper from original symbol names to new symbol names based on a file
  113. /// containing a list of mappings from old name to new name.
  114. class SymbolRemapper {
  115. std::unique_ptr<MemoryBuffer> File;
  116. DenseMap<StringRef, StringRef> RemappingTable;
  117. public:
  118. /// Build a SymbolRemapper from a file containing a list of old/new symbols.
  119. static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
  120. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  121. if (!BufOrError)
  122. exitWithErrorCode(BufOrError.getError(), InputFile);
  123. auto Remapper = llvm::make_unique<SymbolRemapper>();
  124. Remapper->File = std::move(BufOrError.get());
  125. for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
  126. !LineIt.is_at_eof(); ++LineIt) {
  127. std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
  128. if (Parts.first.empty() || Parts.second.empty() ||
  129. Parts.second.count(' ')) {
  130. exitWithError("unexpected line in remapping file",
  131. (InputFile + ":" + Twine(LineIt.line_number())).str(),
  132. "expected 'old_symbol new_symbol'");
  133. }
  134. Remapper->RemappingTable.insert(Parts);
  135. }
  136. return Remapper;
  137. }
  138. /// Attempt to map the given old symbol into a new symbol.
  139. ///
  140. /// \return The new symbol, or \p Name if no such symbol was found.
  141. StringRef operator()(StringRef Name) {
  142. StringRef New = RemappingTable.lookup(Name);
  143. return New.empty() ? Name : New;
  144. }
  145. };
  146. }
  147. struct WeightedFile {
  148. std::string Filename;
  149. uint64_t Weight;
  150. };
  151. typedef SmallVector<WeightedFile, 5> WeightedFileVector;
  152. /// Keep track of merged data and reported errors.
  153. struct WriterContext {
  154. std::mutex Lock;
  155. InstrProfWriter Writer;
  156. Error Err;
  157. std::string ErrWhence;
  158. std::mutex &ErrLock;
  159. SmallSet<instrprof_error, 4> &WriterErrorCodes;
  160. WriterContext(bool IsSparse, std::mutex &ErrLock,
  161. SmallSet<instrprof_error, 4> &WriterErrorCodes)
  162. : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
  163. ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
  164. };
  165. /// Determine whether an error is fatal for profile merging.
  166. static bool isFatalError(instrprof_error IPE) {
  167. switch (IPE) {
  168. default:
  169. return true;
  170. case instrprof_error::success:
  171. case instrprof_error::eof:
  172. case instrprof_error::unknown_function:
  173. case instrprof_error::hash_mismatch:
  174. case instrprof_error::count_mismatch:
  175. case instrprof_error::counter_overflow:
  176. case instrprof_error::value_site_count_mismatch:
  177. return false;
  178. }
  179. }
  180. /// Computer the overlap b/w profile BaseFilename and TestFileName,
  181. /// and store the program level result to Overlap.
  182. static void overlapInput(const std::string &BaseFilename,
  183. const std::string &TestFilename, WriterContext *WC,
  184. OverlapStats &Overlap,
  185. const OverlapFuncFilters &FuncFilter,
  186. raw_fd_ostream &OS, bool IsCS) {
  187. auto ReaderOrErr = InstrProfReader::create(TestFilename);
  188. if (Error E = ReaderOrErr.takeError()) {
  189. // Skip the empty profiles by returning sliently.
  190. instrprof_error IPE = InstrProfError::take(std::move(E));
  191. if (IPE != instrprof_error::empty_raw_profile)
  192. WC->Err = make_error<InstrProfError>(IPE);
  193. return;
  194. }
  195. auto Reader = std::move(ReaderOrErr.get());
  196. for (auto &I : *Reader) {
  197. OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
  198. FuncOverlap.setFuncInfo(I.Name, I.Hash);
  199. WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
  200. FuncOverlap.dump(OS);
  201. }
  202. }
  203. /// Load an input into a writer context.
  204. static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
  205. WriterContext *WC) {
  206. std::unique_lock<std::mutex> CtxGuard{WC->Lock};
  207. // If there's a pending hard error, don't do more work.
  208. if (WC->Err)
  209. return;
  210. // Copy the filename, because llvm::ThreadPool copied the input "const
  211. // WeightedFile &" by value, making a reference to the filename within it
  212. // invalid outside of this packaged task.
  213. WC->ErrWhence = Input.Filename;
  214. auto ReaderOrErr = InstrProfReader::create(Input.Filename);
  215. if (Error E = ReaderOrErr.takeError()) {
  216. // Skip the empty profiles by returning sliently.
  217. instrprof_error IPE = InstrProfError::take(std::move(E));
  218. if (IPE != instrprof_error::empty_raw_profile)
  219. WC->Err = make_error<InstrProfError>(IPE);
  220. return;
  221. }
  222. auto Reader = std::move(ReaderOrErr.get());
  223. bool IsIRProfile = Reader->isIRLevelProfile();
  224. bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
  225. if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
  226. WC->Err = make_error<StringError>(
  227. "Merge IR generated profile with Clang generated profile.",
  228. std::error_code());
  229. return;
  230. }
  231. for (auto &I : *Reader) {
  232. if (Remapper)
  233. I.Name = (*Remapper)(I.Name);
  234. const StringRef FuncName = I.Name;
  235. bool Reported = false;
  236. WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
  237. if (Reported) {
  238. consumeError(std::move(E));
  239. return;
  240. }
  241. Reported = true;
  242. // Only show hint the first time an error occurs.
  243. instrprof_error IPE = InstrProfError::take(std::move(E));
  244. std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
  245. bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
  246. handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
  247. FuncName, firstTime);
  248. });
  249. }
  250. if (Reader->hasError()) {
  251. if (Error E = Reader->getError()) {
  252. instrprof_error IPE = InstrProfError::take(std::move(E));
  253. if (isFatalError(IPE))
  254. WC->Err = make_error<InstrProfError>(IPE);
  255. }
  256. }
  257. }
  258. /// Merge the \p Src writer context into \p Dst.
  259. static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
  260. // If we've already seen a hard error, continuing with the merge would
  261. // clobber it.
  262. if (Dst->Err || Src->Err)
  263. return;
  264. bool Reported = false;
  265. Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
  266. if (Reported) {
  267. consumeError(std::move(E));
  268. return;
  269. }
  270. Reported = true;
  271. Dst->Err = std::move(E);
  272. });
  273. }
  274. static void mergeInstrProfile(const WeightedFileVector &Inputs,
  275. SymbolRemapper *Remapper,
  276. StringRef OutputFilename,
  277. ProfileFormat OutputFormat, bool OutputSparse,
  278. unsigned NumThreads) {
  279. if (OutputFilename.compare("-") == 0)
  280. exitWithError("Cannot write indexed profdata format to stdout.");
  281. if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
  282. OutputFormat != PF_Text)
  283. exitWithError("Unknown format is specified.");
  284. std::mutex ErrorLock;
  285. SmallSet<instrprof_error, 4> WriterErrorCodes;
  286. // If NumThreads is not specified, auto-detect a good default.
  287. if (NumThreads == 0)
  288. NumThreads =
  289. std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
  290. // Initialize the writer contexts.
  291. SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
  292. for (unsigned I = 0; I < NumThreads; ++I)
  293. Contexts.emplace_back(llvm::make_unique<WriterContext>(
  294. OutputSparse, ErrorLock, WriterErrorCodes));
  295. if (NumThreads == 1) {
  296. for (const auto &Input : Inputs)
  297. loadInput(Input, Remapper, Contexts[0].get());
  298. } else {
  299. ThreadPool Pool(NumThreads);
  300. // Load the inputs in parallel (N/NumThreads serial steps).
  301. unsigned Ctx = 0;
  302. for (const auto &Input : Inputs) {
  303. Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
  304. Ctx = (Ctx + 1) % NumThreads;
  305. }
  306. Pool.wait();
  307. // Merge the writer contexts together (~ lg(NumThreads) serial steps).
  308. unsigned Mid = Contexts.size() / 2;
  309. unsigned End = Contexts.size();
  310. assert(Mid > 0 && "Expected more than one context");
  311. do {
  312. for (unsigned I = 0; I < Mid; ++I)
  313. Pool.async(mergeWriterContexts, Contexts[I].get(),
  314. Contexts[I + Mid].get());
  315. Pool.wait();
  316. if (End & 1) {
  317. Pool.async(mergeWriterContexts, Contexts[0].get(),
  318. Contexts[End - 1].get());
  319. Pool.wait();
  320. }
  321. End = Mid;
  322. Mid /= 2;
  323. } while (Mid > 0);
  324. }
  325. // Handle deferred hard errors encountered during merging.
  326. for (std::unique_ptr<WriterContext> &WC : Contexts) {
  327. if (!WC->Err)
  328. continue;
  329. if (!WC->Err.isA<InstrProfError>())
  330. exitWithError(std::move(WC->Err), WC->ErrWhence);
  331. instrprof_error IPE = InstrProfError::take(std::move(WC->Err));
  332. if (isFatalError(IPE))
  333. exitWithError(make_error<InstrProfError>(IPE), WC->ErrWhence);
  334. else
  335. warn(toString(make_error<InstrProfError>(IPE)),
  336. WC->ErrWhence);
  337. }
  338. std::error_code EC;
  339. raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
  340. if (EC)
  341. exitWithErrorCode(EC, OutputFilename);
  342. InstrProfWriter &Writer = Contexts[0]->Writer;
  343. if (OutputFormat == PF_Text) {
  344. if (Error E = Writer.writeText(Output))
  345. exitWithError(std::move(E));
  346. } else {
  347. Writer.write(Output);
  348. }
  349. }
  350. /// Make a copy of the given function samples with all symbol names remapped
  351. /// by the provided symbol remapper.
  352. static sampleprof::FunctionSamples
  353. remapSamples(const sampleprof::FunctionSamples &Samples,
  354. SymbolRemapper &Remapper, sampleprof_error &Error) {
  355. sampleprof::FunctionSamples Result;
  356. Result.setName(Remapper(Samples.getName()));
  357. Result.addTotalSamples(Samples.getTotalSamples());
  358. Result.addHeadSamples(Samples.getHeadSamples());
  359. for (const auto &BodySample : Samples.getBodySamples()) {
  360. Result.addBodySamples(BodySample.first.LineOffset,
  361. BodySample.first.Discriminator,
  362. BodySample.second.getSamples());
  363. for (const auto &Target : BodySample.second.getCallTargets()) {
  364. Result.addCalledTargetSamples(BodySample.first.LineOffset,
  365. BodySample.first.Discriminator,
  366. Remapper(Target.first()), Target.second);
  367. }
  368. }
  369. for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
  370. sampleprof::FunctionSamplesMap &Target =
  371. Result.functionSamplesAt(CallsiteSamples.first);
  372. for (const auto &Callsite : CallsiteSamples.second) {
  373. sampleprof::FunctionSamples Remapped =
  374. remapSamples(Callsite.second, Remapper, Error);
  375. MergeResult(Error, Target[Remapped.getName()].merge(Remapped));
  376. }
  377. }
  378. return Result;
  379. }
  380. static sampleprof::SampleProfileFormat FormatMap[] = {
  381. sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Compact_Binary,
  382. sampleprof::SPF_GCC, sampleprof::SPF_Binary};
  383. static void mergeSampleProfile(const WeightedFileVector &Inputs,
  384. SymbolRemapper *Remapper,
  385. StringRef OutputFilename,
  386. ProfileFormat OutputFormat) {
  387. using namespace sampleprof;
  388. StringMap<FunctionSamples> ProfileMap;
  389. SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
  390. LLVMContext Context;
  391. for (const auto &Input : Inputs) {
  392. auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
  393. if (std::error_code EC = ReaderOrErr.getError())
  394. exitWithErrorCode(EC, Input.Filename);
  395. // We need to keep the readers around until after all the files are
  396. // read so that we do not lose the function names stored in each
  397. // reader's memory. The function names are needed to write out the
  398. // merged profile map.
  399. Readers.push_back(std::move(ReaderOrErr.get()));
  400. const auto Reader = Readers.back().get();
  401. if (std::error_code EC = Reader->read())
  402. exitWithErrorCode(EC, Input.Filename);
  403. StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
  404. for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
  405. E = Profiles.end();
  406. I != E; ++I) {
  407. sampleprof_error Result = sampleprof_error::success;
  408. FunctionSamples Remapped =
  409. Remapper ? remapSamples(I->second, *Remapper, Result)
  410. : FunctionSamples();
  411. FunctionSamples &Samples = Remapper ? Remapped : I->second;
  412. StringRef FName = Samples.getName();
  413. MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
  414. if (Result != sampleprof_error::success) {
  415. std::error_code EC = make_error_code(Result);
  416. handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
  417. }
  418. }
  419. }
  420. auto WriterOrErr =
  421. SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
  422. if (std::error_code EC = WriterOrErr.getError())
  423. exitWithErrorCode(EC, OutputFilename);
  424. auto Writer = std::move(WriterOrErr.get());
  425. Writer->write(ProfileMap);
  426. }
  427. static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
  428. StringRef WeightStr, FileName;
  429. std::tie(WeightStr, FileName) = WeightedFilename.split(',');
  430. uint64_t Weight;
  431. if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
  432. exitWithError("Input weight must be a positive integer.");
  433. return {FileName, Weight};
  434. }
  435. static std::unique_ptr<MemoryBuffer>
  436. getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
  437. if (InputFilenamesFile == "")
  438. return {};
  439. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
  440. if (!BufOrError)
  441. exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
  442. return std::move(*BufOrError);
  443. }
  444. static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
  445. StringRef Filename = WF.Filename;
  446. uint64_t Weight = WF.Weight;
  447. // If it's STDIN just pass it on.
  448. if (Filename == "-") {
  449. WNI.push_back({Filename, Weight});
  450. return;
  451. }
  452. llvm::sys::fs::file_status Status;
  453. llvm::sys::fs::status(Filename, Status);
  454. if (!llvm::sys::fs::exists(Status))
  455. exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
  456. Filename);
  457. // If it's a source file, collect it.
  458. if (llvm::sys::fs::is_regular_file(Status)) {
  459. WNI.push_back({Filename, Weight});
  460. return;
  461. }
  462. if (llvm::sys::fs::is_directory(Status)) {
  463. std::error_code EC;
  464. for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
  465. F != E && !EC; F.increment(EC)) {
  466. if (llvm::sys::fs::is_regular_file(F->path())) {
  467. addWeightedInput(WNI, {F->path(), Weight});
  468. }
  469. }
  470. if (EC)
  471. exitWithErrorCode(EC, Filename);
  472. }
  473. }
  474. static void parseInputFilenamesFile(MemoryBuffer *Buffer,
  475. WeightedFileVector &WFV) {
  476. if (!Buffer)
  477. return;
  478. SmallVector<StringRef, 8> Entries;
  479. StringRef Data = Buffer->getBuffer();
  480. Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  481. for (const StringRef &FileWeightEntry : Entries) {
  482. StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
  483. // Skip comments.
  484. if (SanitizedEntry.startswith("#"))
  485. continue;
  486. // If there's no comma, it's an unweighted profile.
  487. else if (SanitizedEntry.find(',') == StringRef::npos)
  488. addWeightedInput(WFV, {SanitizedEntry, 1});
  489. else
  490. addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
  491. }
  492. }
  493. static int merge_main(int argc, const char *argv[]) {
  494. cl::list<std::string> InputFilenames(cl::Positional,
  495. cl::desc("<filename...>"));
  496. cl::list<std::string> WeightedInputFilenames("weighted-input",
  497. cl::desc("<weight>,<filename>"));
  498. cl::opt<std::string> InputFilenamesFile(
  499. "input-files", cl::init(""),
  500. cl::desc("Path to file containing newline-separated "
  501. "[<weight>,]<filename> entries"));
  502. cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
  503. cl::aliasopt(InputFilenamesFile));
  504. cl::opt<bool> DumpInputFileList(
  505. "dump-input-file-list", cl::init(false), cl::Hidden,
  506. cl::desc("Dump the list of input files and their weights, then exit"));
  507. cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
  508. cl::desc("Symbol remapping file"));
  509. cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
  510. cl::aliasopt(RemappingFile));
  511. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  512. cl::init("-"), cl::Required,
  513. cl::desc("Output file"));
  514. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  515. cl::aliasopt(OutputFilename));
  516. cl::opt<ProfileKinds> ProfileKind(
  517. cl::desc("Profile kind:"), cl::init(instr),
  518. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  519. clEnumVal(sample, "Sample profile")));
  520. cl::opt<ProfileFormat> OutputFormat(
  521. cl::desc("Format of output profile"), cl::init(PF_Binary),
  522. cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
  523. clEnumValN(PF_Compact_Binary, "compbinary",
  524. "Compact binary encoding"),
  525. clEnumValN(PF_Text, "text", "Text encoding"),
  526. clEnumValN(PF_GCC, "gcc",
  527. "GCC encoding (only meaningful for -sample)")));
  528. cl::opt<bool> OutputSparse("sparse", cl::init(false),
  529. cl::desc("Generate a sparse profile (only meaningful for -instr)"));
  530. cl::opt<unsigned> NumThreads(
  531. "num-threads", cl::init(0),
  532. cl::desc("Number of merge threads to use (default: autodetect)"));
  533. cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
  534. cl::aliasopt(NumThreads));
  535. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
  536. WeightedFileVector WeightedInputs;
  537. for (StringRef Filename : InputFilenames)
  538. addWeightedInput(WeightedInputs, {Filename, 1});
  539. for (StringRef WeightedFilename : WeightedInputFilenames)
  540. addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
  541. // Make sure that the file buffer stays alive for the duration of the
  542. // weighted input vector's lifetime.
  543. auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
  544. parseInputFilenamesFile(Buffer.get(), WeightedInputs);
  545. if (WeightedInputs.empty())
  546. exitWithError("No input files specified. See " +
  547. sys::path::filename(argv[0]) + " -help");
  548. if (DumpInputFileList) {
  549. for (auto &WF : WeightedInputs)
  550. outs() << WF.Weight << "," << WF.Filename << "\n";
  551. return 0;
  552. }
  553. std::unique_ptr<SymbolRemapper> Remapper;
  554. if (!RemappingFile.empty())
  555. Remapper = SymbolRemapper::create(RemappingFile);
  556. if (ProfileKind == instr)
  557. mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
  558. OutputFormat, OutputSparse, NumThreads);
  559. else
  560. mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
  561. OutputFormat);
  562. return 0;
  563. }
  564. /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
  565. static void overlapInstrProfile(const std::string &BaseFilename,
  566. const std::string &TestFilename,
  567. const OverlapFuncFilters &FuncFilter,
  568. raw_fd_ostream &OS, bool IsCS) {
  569. std::mutex ErrorLock;
  570. SmallSet<instrprof_error, 4> WriterErrorCodes;
  571. WriterContext Context(false, ErrorLock, WriterErrorCodes);
  572. WeightedFile WeightedInput{BaseFilename, 1};
  573. OverlapStats Overlap;
  574. Error E = Overlap.accumuateCounts(BaseFilename, TestFilename, IsCS);
  575. if (E)
  576. exitWithError(std::move(E), "Error in getting profile count sums");
  577. if (Overlap.Base.CountSum < 1.0f) {
  578. OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
  579. exit(0);
  580. }
  581. if (Overlap.Test.CountSum < 1.0f) {
  582. OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
  583. exit(0);
  584. }
  585. loadInput(WeightedInput, nullptr, &Context);
  586. overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
  587. IsCS);
  588. Overlap.dump(OS);
  589. }
  590. static int overlap_main(int argc, const char *argv[]) {
  591. cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
  592. cl::desc("<base profile file>"));
  593. cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
  594. cl::desc("<test profile file>"));
  595. cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
  596. cl::desc("Output file"));
  597. cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
  598. cl::opt<bool> IsCS("cs", cl::init(false),
  599. cl::desc("For context sensitive counts"));
  600. cl::opt<unsigned long long> ValueCutoff(
  601. "value-cutoff", cl::init(-1),
  602. cl::desc(
  603. "Function level overlap information for every function in test "
  604. "profile with max count value greater then the parameter value"));
  605. cl::opt<std::string> FuncNameFilter(
  606. "function",
  607. cl::desc("Function level overlap information for matching functions"));
  608. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
  609. std::error_code EC;
  610. raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
  611. if (EC)
  612. exitWithErrorCode(EC, Output);
  613. overlapInstrProfile(BaseFilename, TestFilename,
  614. OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
  615. IsCS);
  616. return 0;
  617. }
  618. typedef struct ValueSitesStats {
  619. ValueSitesStats()
  620. : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
  621. TotalNumValues(0) {}
  622. uint64_t TotalNumValueSites;
  623. uint64_t TotalNumValueSitesWithValueProfile;
  624. uint64_t TotalNumValues;
  625. std::vector<unsigned> ValueSitesHistogram;
  626. } ValueSitesStats;
  627. static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
  628. ValueSitesStats &Stats, raw_fd_ostream &OS,
  629. InstrProfSymtab *Symtab) {
  630. uint32_t NS = Func.getNumValueSites(VK);
  631. Stats.TotalNumValueSites += NS;
  632. for (size_t I = 0; I < NS; ++I) {
  633. uint32_t NV = Func.getNumValueDataForSite(VK, I);
  634. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
  635. Stats.TotalNumValues += NV;
  636. if (NV) {
  637. Stats.TotalNumValueSitesWithValueProfile++;
  638. if (NV > Stats.ValueSitesHistogram.size())
  639. Stats.ValueSitesHistogram.resize(NV, 0);
  640. Stats.ValueSitesHistogram[NV - 1]++;
  641. }
  642. uint64_t SiteSum = 0;
  643. for (uint32_t V = 0; V < NV; V++)
  644. SiteSum += VD[V].Count;
  645. if (SiteSum == 0)
  646. SiteSum = 1;
  647. for (uint32_t V = 0; V < NV; V++) {
  648. OS << "\t[ " << format("%2u", I) << ", ";
  649. if (Symtab == nullptr)
  650. OS << format("%4" PRIu64, VD[V].Value);
  651. else
  652. OS << Symtab->getFuncName(VD[V].Value);
  653. OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
  654. << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
  655. }
  656. }
  657. }
  658. static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
  659. ValueSitesStats &Stats) {
  660. OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
  661. OS << " Total number of sites with values: "
  662. << Stats.TotalNumValueSitesWithValueProfile << "\n";
  663. OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
  664. OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
  665. for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
  666. if (Stats.ValueSitesHistogram[I] > 0)
  667. OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
  668. }
  669. }
  670. static int showInstrProfile(const std::string &Filename, bool ShowCounts,
  671. uint32_t TopN, bool ShowIndirectCallTargets,
  672. bool ShowMemOPSizes, bool ShowDetailedSummary,
  673. std::vector<uint32_t> DetailedSummaryCutoffs,
  674. bool ShowAllFunctions, bool ShowCS,
  675. uint64_t ValueCutoff, bool OnlyListBelow,
  676. const std::string &ShowFunction, bool TextFormat,
  677. raw_fd_ostream &OS) {
  678. auto ReaderOrErr = InstrProfReader::create(Filename);
  679. std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
  680. if (ShowDetailedSummary && Cutoffs.empty()) {
  681. Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
  682. }
  683. InstrProfSummaryBuilder Builder(std::move(Cutoffs));
  684. if (Error E = ReaderOrErr.takeError())
  685. exitWithError(std::move(E), Filename);
  686. auto Reader = std::move(ReaderOrErr.get());
  687. bool IsIRInstr = Reader->isIRLevelProfile();
  688. size_t ShownFunctions = 0;
  689. size_t BelowCutoffFunctions = 0;
  690. int NumVPKind = IPVK_Last - IPVK_First + 1;
  691. std::vector<ValueSitesStats> VPStats(NumVPKind);
  692. auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
  693. const std::pair<std::string, uint64_t> &v2) {
  694. return v1.second > v2.second;
  695. };
  696. std::priority_queue<std::pair<std::string, uint64_t>,
  697. std::vector<std::pair<std::string, uint64_t>>,
  698. decltype(MinCmp)>
  699. HottestFuncs(MinCmp);
  700. if (!TextFormat && OnlyListBelow) {
  701. OS << "The list of functions with the maximum counter less than "
  702. << ValueCutoff << ":\n";
  703. }
  704. // Add marker so that IR-level instrumentation round-trips properly.
  705. if (TextFormat && IsIRInstr)
  706. OS << ":ir\n";
  707. for (const auto &Func : *Reader) {
  708. if (Reader->isIRLevelProfile()) {
  709. bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
  710. if (FuncIsCS != ShowCS)
  711. continue;
  712. }
  713. bool Show =
  714. ShowAllFunctions || (!ShowFunction.empty() &&
  715. Func.Name.find(ShowFunction) != Func.Name.npos);
  716. bool doTextFormatDump = (Show && TextFormat);
  717. if (doTextFormatDump) {
  718. InstrProfSymtab &Symtab = Reader->getSymtab();
  719. InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
  720. OS);
  721. continue;
  722. }
  723. assert(Func.Counts.size() > 0 && "function missing entry counter");
  724. Builder.addRecord(Func);
  725. uint64_t FuncMax = 0;
  726. uint64_t FuncSum = 0;
  727. for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
  728. FuncMax = std::max(FuncMax, Func.Counts[I]);
  729. FuncSum += Func.Counts[I];
  730. }
  731. if (FuncMax < ValueCutoff) {
  732. ++BelowCutoffFunctions;
  733. if (OnlyListBelow) {
  734. OS << " " << Func.Name << ": (Max = " << FuncMax
  735. << " Sum = " << FuncSum << ")\n";
  736. }
  737. continue;
  738. } else if (OnlyListBelow)
  739. continue;
  740. if (TopN) {
  741. if (HottestFuncs.size() == TopN) {
  742. if (HottestFuncs.top().second < FuncMax) {
  743. HottestFuncs.pop();
  744. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  745. }
  746. } else
  747. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  748. }
  749. if (Show) {
  750. if (!ShownFunctions)
  751. OS << "Counters:\n";
  752. ++ShownFunctions;
  753. OS << " " << Func.Name << ":\n"
  754. << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
  755. << " Counters: " << Func.Counts.size() << "\n";
  756. if (!IsIRInstr)
  757. OS << " Function count: " << Func.Counts[0] << "\n";
  758. if (ShowIndirectCallTargets)
  759. OS << " Indirect Call Site Count: "
  760. << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
  761. uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
  762. if (ShowMemOPSizes && NumMemOPCalls > 0)
  763. OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
  764. << "\n";
  765. if (ShowCounts) {
  766. OS << " Block counts: [";
  767. size_t Start = (IsIRInstr ? 0 : 1);
  768. for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
  769. OS << (I == Start ? "" : ", ") << Func.Counts[I];
  770. }
  771. OS << "]\n";
  772. }
  773. if (ShowIndirectCallTargets) {
  774. OS << " Indirect Target Results:\n";
  775. traverseAllValueSites(Func, IPVK_IndirectCallTarget,
  776. VPStats[IPVK_IndirectCallTarget], OS,
  777. &(Reader->getSymtab()));
  778. }
  779. if (ShowMemOPSizes && NumMemOPCalls > 0) {
  780. OS << " Memory Intrinsic Size Results:\n";
  781. traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
  782. nullptr);
  783. }
  784. }
  785. }
  786. if (Reader->hasError())
  787. exitWithError(Reader->getError(), Filename);
  788. if (TextFormat)
  789. return 0;
  790. std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
  791. OS << "Instrumentation level: "
  792. << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
  793. if (ShowAllFunctions || !ShowFunction.empty())
  794. OS << "Functions shown: " << ShownFunctions << "\n";
  795. OS << "Total functions: " << PS->getNumFunctions() << "\n";
  796. if (ValueCutoff > 0) {
  797. OS << "Number of functions with maximum count (< " << ValueCutoff
  798. << "): " << BelowCutoffFunctions << "\n";
  799. OS << "Number of functions with maximum count (>= " << ValueCutoff
  800. << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
  801. }
  802. OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
  803. OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
  804. if (TopN) {
  805. std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
  806. while (!HottestFuncs.empty()) {
  807. SortedHottestFuncs.emplace_back(HottestFuncs.top());
  808. HottestFuncs.pop();
  809. }
  810. OS << "Top " << TopN
  811. << " functions with the largest internal block counts: \n";
  812. for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
  813. OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
  814. }
  815. if (ShownFunctions && ShowIndirectCallTargets) {
  816. OS << "Statistics for indirect call sites profile:\n";
  817. showValueSitesStats(OS, IPVK_IndirectCallTarget,
  818. VPStats[IPVK_IndirectCallTarget]);
  819. }
  820. if (ShownFunctions && ShowMemOPSizes) {
  821. OS << "Statistics for memory intrinsic calls sizes profile:\n";
  822. showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
  823. }
  824. if (ShowDetailedSummary) {
  825. OS << "Detailed summary:\n";
  826. OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
  827. OS << "Total count: " << PS->getTotalCount() << "\n";
  828. for (auto Entry : PS->getDetailedSummary()) {
  829. OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
  830. << " account for "
  831. << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
  832. << " percentage of the total counts.\n";
  833. }
  834. }
  835. return 0;
  836. }
  837. static int showSampleProfile(const std::string &Filename, bool ShowCounts,
  838. bool ShowAllFunctions,
  839. const std::string &ShowFunction,
  840. raw_fd_ostream &OS) {
  841. using namespace sampleprof;
  842. LLVMContext Context;
  843. auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
  844. if (std::error_code EC = ReaderOrErr.getError())
  845. exitWithErrorCode(EC, Filename);
  846. auto Reader = std::move(ReaderOrErr.get());
  847. if (std::error_code EC = Reader->read())
  848. exitWithErrorCode(EC, Filename);
  849. if (ShowAllFunctions || ShowFunction.empty())
  850. Reader->dump(OS);
  851. else
  852. Reader->dumpFunctionProfile(ShowFunction, OS);
  853. return 0;
  854. }
  855. static int show_main(int argc, const char *argv[]) {
  856. cl::opt<std::string> Filename(cl::Positional, cl::Required,
  857. cl::desc("<profdata-file>"));
  858. cl::opt<bool> ShowCounts("counts", cl::init(false),
  859. cl::desc("Show counter values for shown functions"));
  860. cl::opt<bool> TextFormat(
  861. "text", cl::init(false),
  862. cl::desc("Show instr profile data in text dump format"));
  863. cl::opt<bool> ShowIndirectCallTargets(
  864. "ic-targets", cl::init(false),
  865. cl::desc("Show indirect call site target values for shown functions"));
  866. cl::opt<bool> ShowMemOPSizes(
  867. "memop-sizes", cl::init(false),
  868. cl::desc("Show the profiled sizes of the memory intrinsic calls "
  869. "for shown functions"));
  870. cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
  871. cl::desc("Show detailed profile summary"));
  872. cl::list<uint32_t> DetailedSummaryCutoffs(
  873. cl::CommaSeparated, "detailed-summary-cutoffs",
  874. cl::desc(
  875. "Cutoff percentages (times 10000) for generating detailed summary"),
  876. cl::value_desc("800000,901000,999999"));
  877. cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
  878. cl::desc("Details for every function"));
  879. cl::opt<bool> ShowCS("showcs", cl::init(false),
  880. cl::desc("Show context sensitive counts"));
  881. cl::opt<std::string> ShowFunction("function",
  882. cl::desc("Details for matching functions"));
  883. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  884. cl::init("-"), cl::desc("Output file"));
  885. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  886. cl::aliasopt(OutputFilename));
  887. cl::opt<ProfileKinds> ProfileKind(
  888. cl::desc("Profile kind:"), cl::init(instr),
  889. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  890. clEnumVal(sample, "Sample profile")));
  891. cl::opt<uint32_t> TopNFunctions(
  892. "topn", cl::init(0),
  893. cl::desc("Show the list of functions with the largest internal counts"));
  894. cl::opt<uint32_t> ValueCutoff(
  895. "value-cutoff", cl::init(0),
  896. cl::desc("Set the count value cutoff. Functions with the maximum count "
  897. "less than this value will not be printed out. (Default is 0)"));
  898. cl::opt<bool> OnlyListBelow(
  899. "list-below-cutoff", cl::init(false),
  900. cl::desc("Only output names of functions whose max count values are "
  901. "below the cutoff value"));
  902. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
  903. if (OutputFilename.empty())
  904. OutputFilename = "-";
  905. if (!Filename.compare(OutputFilename)) {
  906. errs() << sys::path::filename(argv[0])
  907. << ": Input file name cannot be the same as the output file name!\n";
  908. return 1;
  909. }
  910. std::error_code EC;
  911. raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
  912. if (EC)
  913. exitWithErrorCode(EC, OutputFilename);
  914. if (ShowAllFunctions && !ShowFunction.empty())
  915. WithColor::warning() << "-function argument ignored: showing all functions\n";
  916. if (ProfileKind == instr)
  917. return showInstrProfile(Filename, ShowCounts, TopNFunctions,
  918. ShowIndirectCallTargets, ShowMemOPSizes,
  919. ShowDetailedSummary, DetailedSummaryCutoffs,
  920. ShowAllFunctions, ShowCS, ValueCutoff,
  921. OnlyListBelow, ShowFunction, TextFormat, OS);
  922. else
  923. return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
  924. ShowFunction, OS);
  925. }
  926. int main(int argc, const char *argv[]) {
  927. InitLLVM X(argc, argv);
  928. StringRef ProgName(sys::path::filename(argv[0]));
  929. if (argc > 1) {
  930. int (*func)(int, const char *[]) = nullptr;
  931. if (strcmp(argv[1], "merge") == 0)
  932. func = merge_main;
  933. else if (strcmp(argv[1], "show") == 0)
  934. func = show_main;
  935. else if (strcmp(argv[1], "overlap") == 0)
  936. func = overlap_main;
  937. if (func) {
  938. std::string Invocation(ProgName.str() + " " + argv[1]);
  939. argv[1] = Invocation.c_str();
  940. return func(argc - 1, argv + 1);
  941. }
  942. if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
  943. strcmp(argv[1], "--help") == 0) {
  944. errs() << "OVERVIEW: LLVM profile data tools\n\n"
  945. << "USAGE: " << ProgName << " <command> [args...]\n"
  946. << "USAGE: " << ProgName << " <command> -help\n\n"
  947. << "See each individual command --help for more details.\n"
  948. << "Available commands: merge, show, overlap\n";
  949. return 0;
  950. }
  951. }
  952. if (argc < 2)
  953. errs() << ProgName << ": No command specified!\n";
  954. else
  955. errs() << ProgName << ": Unknown command!\n";
  956. errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
  957. return 1;
  958. }