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 
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/FormattedStream.h"
27 #include "llvm/Support/InitLLVM.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/ThreadPool.h"
31 #include "llvm/Support/Threading.h"
32 #include "llvm/Support/WithColor.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <algorithm>
35 
36 using namespace llvm;
37 
38 enum ProfileFormat {
39   PF_None = 0,
40   PF_Text,
41   PF_Compact_Binary,
42   PF_Ext_Binary,
43   PF_GCC,
44   PF_Binary
45 };
46 
47 static void warn(Twine Message, std::string Whence = "",
48                  std::string Hint = "") {
49   WithColor::warning();
50   if (!Whence.empty())
51     errs() << Whence << ": ";
52   errs() << Message << "\n";
53   if (!Hint.empty())
54     WithColor::note() << Hint << "\n";
55 }
56 
57 static void exitWithError(Twine Message, std::string Whence = "",
58                           std::string Hint = "") {
59   WithColor::error();
60   if (!Whence.empty())
61     errs() << Whence << ": ";
62   errs() << Message << "\n";
63   if (!Hint.empty())
64     WithColor::note() << Hint << "\n";
65   ::exit(1);
66 }
67 
68 static void exitWithError(Error E, StringRef Whence = "") {
69   if (E.isA<InstrProfError>()) {
70     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
71       instrprof_error instrError = IPE.get();
72       StringRef Hint = "";
73       if (instrError == instrprof_error::unrecognized_format) {
74         // Hint for common error of forgetting --sample for sample profiles.
75         Hint = "Perhaps you forgot to use the --sample option?";
76       }
77       exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
78     });
79   }
80 
81   exitWithError(toString(std::move(E)), std::string(Whence));
82 }
83 
84 static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
85   exitWithError(EC.message(), std::string(Whence));
86 }
87 
88 namespace {
89 enum ProfileKinds { instr, sample };
90 enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
91 }
92 
93 static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
94                                  StringRef Whence = "") {
95   if (FailMode == failIfAnyAreInvalid)
96     exitWithErrorCode(EC, Whence);
97   else
98     warn(EC.message(), std::string(Whence));
99 }
100 
101 static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
102                                    StringRef WhenceFunction = "",
103                                    bool ShowHint = true) {
104   if (!WhenceFile.empty())
105     errs() << WhenceFile << ": ";
106   if (!WhenceFunction.empty())
107     errs() << WhenceFunction << ": ";
108 
109   auto IPE = instrprof_error::success;
110   E = handleErrors(std::move(E),
111                    [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
112                      IPE = E->get();
113                      return Error(std::move(E));
114                    });
115   errs() << toString(std::move(E)) << "\n";
116 
117   if (ShowHint) {
118     StringRef Hint = "";
119     if (IPE != instrprof_error::success) {
120       switch (IPE) {
121       case instrprof_error::hash_mismatch:
122       case instrprof_error::count_mismatch:
123       case instrprof_error::value_site_count_mismatch:
124         Hint = "Make sure that all profile data to be merged is generated "
125                "from the same binary.";
126         break;
127       default:
128         break;
129       }
130     }
131 
132     if (!Hint.empty())
133       errs() << Hint << "\n";
134   }
135 }
136 
137 namespace {
138 /// A remapper from original symbol names to new symbol names based on a file
139 /// containing a list of mappings from old name to new name.
140 class SymbolRemapper {
141   std::unique_ptr<MemoryBuffer> File;
142   DenseMap<StringRef, StringRef> RemappingTable;
143 
144 public:
145   /// Build a SymbolRemapper from a file containing a list of old/new symbols.
146   static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
147     auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
148     if (!BufOrError)
149       exitWithErrorCode(BufOrError.getError(), InputFile);
150 
151     auto Remapper = std::make_unique<SymbolRemapper>();
152     Remapper->File = std::move(BufOrError.get());
153 
154     for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
155          !LineIt.is_at_eof(); ++LineIt) {
156       std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
157       if (Parts.first.empty() || Parts.second.empty() ||
158           Parts.second.count(' ')) {
159         exitWithError("unexpected line in remapping file",
160                       (InputFile + ":" + Twine(LineIt.line_number())).str(),
161                       "expected 'old_symbol new_symbol'");
162       }
163       Remapper->RemappingTable.insert(Parts);
164     }
165     return Remapper;
166   }
167 
168   /// Attempt to map the given old symbol into a new symbol.
169   ///
170   /// \return The new symbol, or \p Name if no such symbol was found.
171   StringRef operator()(StringRef Name) {
172     StringRef New = RemappingTable.lookup(Name);
173     return New.empty() ? Name : New;
174   }
175 };
176 }
177 
178 struct WeightedFile {
179   std::string Filename;
180   uint64_t Weight;
181 };
182 typedef SmallVector<WeightedFile, 5> WeightedFileVector;
183 
184 /// Keep track of merged data and reported errors.
185 struct WriterContext {
186   std::mutex Lock;
187   InstrProfWriter Writer;
188   std::vector<std::pair<Error, std::string>> Errors;
189   std::mutex &ErrLock;
190   SmallSet<instrprof_error, 4> &WriterErrorCodes;
191 
192   WriterContext(bool IsSparse, std::mutex &ErrLock,
193                 SmallSet<instrprof_error, 4> &WriterErrorCodes)
194       : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
195         WriterErrorCodes(WriterErrorCodes) {}
196 };
197 
198 /// Computer the overlap b/w profile BaseFilename and TestFileName,
199 /// and store the program level result to Overlap.
200 static void overlapInput(const std::string &BaseFilename,
201                          const std::string &TestFilename, WriterContext *WC,
202                          OverlapStats &Overlap,
203                          const OverlapFuncFilters &FuncFilter,
204                          raw_fd_ostream &OS, bool IsCS) {
205   auto ReaderOrErr = InstrProfReader::create(TestFilename);
206   if (Error E = ReaderOrErr.takeError()) {
207     // Skip the empty profiles by returning sliently.
208     instrprof_error IPE = InstrProfError::take(std::move(E));
209     if (IPE != instrprof_error::empty_raw_profile)
210       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
211     return;
212   }
213 
214   auto Reader = std::move(ReaderOrErr.get());
215   for (auto &I : *Reader) {
216     OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
217     FuncOverlap.setFuncInfo(I.Name, I.Hash);
218 
219     WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
220     FuncOverlap.dump(OS);
221   }
222 }
223 
224 /// Load an input into a writer context.
225 static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
226                       WriterContext *WC) {
227   std::unique_lock<std::mutex> CtxGuard{WC->Lock};
228 
229   // Copy the filename, because llvm::ThreadPool copied the input "const
230   // WeightedFile &" by value, making a reference to the filename within it
231   // invalid outside of this packaged task.
232   std::string Filename = Input.Filename;
233 
234   auto ReaderOrErr = InstrProfReader::create(Input.Filename);
235   if (Error E = ReaderOrErr.takeError()) {
236     // Skip the empty profiles by returning sliently.
237     instrprof_error IPE = InstrProfError::take(std::move(E));
238     if (IPE != instrprof_error::empty_raw_profile)
239       WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
240     return;
241   }
242 
243   auto Reader = std::move(ReaderOrErr.get());
244   bool IsIRProfile = Reader->isIRLevelProfile();
245   bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
246   if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
247     WC->Errors.emplace_back(
248         make_error<StringError>(
249             "Merge IR generated profile with Clang generated profile.",
250             std::error_code()),
251         Filename);
252     return;
253   }
254   WC->Writer.setInstrEntryBBEnabled(Reader->instrEntryBBEnabled());
255 
256   for (auto &I : *Reader) {
257     if (Remapper)
258       I.Name = (*Remapper)(I.Name);
259     const StringRef FuncName = I.Name;
260     bool Reported = false;
261     WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
262       if (Reported) {
263         consumeError(std::move(E));
264         return;
265       }
266       Reported = true;
267       // Only show hint the first time an error occurs.
268       instrprof_error IPE = InstrProfError::take(std::move(E));
269       std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
270       bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
271       handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
272                              FuncName, firstTime);
273     });
274   }
275   if (Reader->hasError())
276     if (Error E = Reader->getError())
277       WC->Errors.emplace_back(std::move(E), Filename);
278 }
279 
280 /// Merge the \p Src writer context into \p Dst.
281 static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
282   for (auto &ErrorPair : Src->Errors)
283     Dst->Errors.push_back(std::move(ErrorPair));
284   Src->Errors.clear();
285 
286   Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
287     instrprof_error IPE = InstrProfError::take(std::move(E));
288     std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
289     bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
290     if (firstTime)
291       warn(toString(make_error<InstrProfError>(IPE)));
292   });
293 }
294 
295 static void writeInstrProfile(StringRef OutputFilename,
296                               ProfileFormat OutputFormat,
297                               InstrProfWriter &Writer) {
298   std::error_code EC;
299   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
300   if (EC)
301     exitWithErrorCode(EC, OutputFilename);
302 
303   if (OutputFormat == PF_Text) {
304     if (Error E = Writer.writeText(Output))
305       exitWithError(std::move(E));
306   } else {
307     Writer.write(Output);
308   }
309 }
310 
311 static void mergeInstrProfile(const WeightedFileVector &Inputs,
312                               SymbolRemapper *Remapper,
313                               StringRef OutputFilename,
314                               ProfileFormat OutputFormat, bool OutputSparse,
315                               unsigned NumThreads, FailureMode FailMode) {
316   if (OutputFilename.compare("-") == 0)
317     exitWithError("Cannot write indexed profdata format to stdout.");
318 
319   if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
320       OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
321     exitWithError("Unknown format is specified.");
322 
323   std::mutex ErrorLock;
324   SmallSet<instrprof_error, 4> WriterErrorCodes;
325 
326   // If NumThreads is not specified, auto-detect a good default.
327   if (NumThreads == 0)
328     NumThreads = std::min(hardware_concurrency().compute_thread_count(),
329                           unsigned((Inputs.size() + 1) / 2));
330   // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails
331   // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't
332   // merged, thus the emitted file ends up with a PF_Unknown kind.
333 
334   // Initialize the writer contexts.
335   SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
336   for (unsigned I = 0; I < NumThreads; ++I)
337     Contexts.emplace_back(std::make_unique<WriterContext>(
338         OutputSparse, ErrorLock, WriterErrorCodes));
339 
340   if (NumThreads == 1) {
341     for (const auto &Input : Inputs)
342       loadInput(Input, Remapper, Contexts[0].get());
343   } else {
344     ThreadPool Pool(hardware_concurrency(NumThreads));
345 
346     // Load the inputs in parallel (N/NumThreads serial steps).
347     unsigned Ctx = 0;
348     for (const auto &Input : Inputs) {
349       Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
350       Ctx = (Ctx + 1) % NumThreads;
351     }
352     Pool.wait();
353 
354     // Merge the writer contexts together (~ lg(NumThreads) serial steps).
355     unsigned Mid = Contexts.size() / 2;
356     unsigned End = Contexts.size();
357     assert(Mid > 0 && "Expected more than one context");
358     do {
359       for (unsigned I = 0; I < Mid; ++I)
360         Pool.async(mergeWriterContexts, Contexts[I].get(),
361                    Contexts[I + Mid].get());
362       Pool.wait();
363       if (End & 1) {
364         Pool.async(mergeWriterContexts, Contexts[0].get(),
365                    Contexts[End - 1].get());
366         Pool.wait();
367       }
368       End = Mid;
369       Mid /= 2;
370     } while (Mid > 0);
371   }
372 
373   // Handle deferred errors encountered during merging. If the number of errors
374   // is equal to the number of inputs the merge failed.
375   unsigned NumErrors = 0;
376   for (std::unique_ptr<WriterContext> &WC : Contexts) {
377     for (auto &ErrorPair : WC->Errors) {
378       ++NumErrors;
379       warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
380     }
381   }
382   if (NumErrors == Inputs.size() ||
383       (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
384     exitWithError("No profiles could be merged.");
385 
386   writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
387 }
388 
389 /// The profile entry for a function in instrumentation profile.
390 struct InstrProfileEntry {
391   uint64_t MaxCount = 0;
392   float ZeroCounterRatio = 0.0;
393   InstrProfRecord *ProfRecord;
394   InstrProfileEntry(InstrProfRecord *Record);
395   InstrProfileEntry() = default;
396 };
397 
398 InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
399   ProfRecord = Record;
400   uint64_t CntNum = Record->Counts.size();
401   uint64_t ZeroCntNum = 0;
402   for (size_t I = 0; I < CntNum; ++I) {
403     MaxCount = std::max(MaxCount, Record->Counts[I]);
404     ZeroCntNum += !Record->Counts[I];
405   }
406   ZeroCounterRatio = (float)ZeroCntNum / CntNum;
407 }
408 
409 /// Either set all the counters in the instr profile entry \p IFE to -1
410 /// in order to drop the profile or scale up the counters in \p IFP to
411 /// be above hot threshold. We use the ratio of zero counters in the
412 /// profile of a function to decide the profile is helpful or harmful
413 /// for performance, and to choose whether to scale up or drop it.
414 static void updateInstrProfileEntry(InstrProfileEntry &IFE,
415                                     uint64_t HotInstrThreshold,
416                                     float ZeroCounterThreshold) {
417   InstrProfRecord *ProfRecord = IFE.ProfRecord;
418   if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
419     // If all or most of the counters of the function are zero, the
420     // profile is unaccountable and shuld be dropped. Reset all the
421     // counters to be -1 and PGO profile-use will drop the profile.
422     // All counters being -1 also implies that the function is hot so
423     // PGO profile-use will also set the entry count metadata to be
424     // above hot threshold.
425     for (size_t I = 0; I < ProfRecord->Counts.size(); ++I)
426       ProfRecord->Counts[I] = -1;
427     return;
428   }
429 
430   // Scale up the MaxCount to be multiple times above hot threshold.
431   const unsigned MultiplyFactor = 3;
432   uint64_t Numerator = HotInstrThreshold * MultiplyFactor;
433   uint64_t Denominator = IFE.MaxCount;
434   ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
435     warn(toString(make_error<InstrProfError>(E)));
436   });
437 }
438 
439 const uint64_t ColdPercentileIdx = 15;
440 const uint64_t HotPercentileIdx = 11;
441 
442 /// Adjust the instr profile in \p WC based on the sample profile in
443 /// \p Reader.
444 static void
445 adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
446                    std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
447                    unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
448                    unsigned InstrProfColdThreshold) {
449   // Function to its entry in instr profile.
450   StringMap<InstrProfileEntry> InstrProfileMap;
451   InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
452   for (auto &PD : WC->Writer.getProfileData()) {
453     // Populate IPBuilder.
454     for (const auto &PDV : PD.getValue()) {
455       InstrProfRecord Record = PDV.second;
456       IPBuilder.addRecord(Record);
457     }
458 
459     // If a function has multiple entries in instr profile, skip it.
460     if (PD.getValue().size() != 1)
461       continue;
462 
463     // Initialize InstrProfileMap.
464     InstrProfRecord *R = &PD.getValue().begin()->second;
465     InstrProfileMap[PD.getKey()] = InstrProfileEntry(R);
466   }
467 
468   ProfileSummary InstrPS = *IPBuilder.getSummary();
469   ProfileSummary SamplePS = Reader->getSummary();
470 
471   // Compute cold thresholds for instr profile and sample profile.
472   uint64_t ColdSampleThreshold =
473       ProfileSummaryBuilder::getEntryForPercentile(
474           SamplePS.getDetailedSummary(),
475           ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
476           .MinCount;
477   uint64_t HotInstrThreshold =
478       ProfileSummaryBuilder::getEntryForPercentile(
479           InstrPS.getDetailedSummary(),
480           ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
481           .MinCount;
482   uint64_t ColdInstrThreshold =
483       InstrProfColdThreshold
484           ? InstrProfColdThreshold
485           : ProfileSummaryBuilder::getEntryForPercentile(
486                 InstrPS.getDetailedSummary(),
487                 ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
488                 .MinCount;
489 
490   // Find hot/warm functions in sample profile which is cold in instr profile
491   // and adjust the profiles of those functions in the instr profile.
492   for (const auto &PD : Reader->getProfiles()) {
493     StringRef FName = PD.getKey();
494     const sampleprof::FunctionSamples &FS = PD.getValue();
495     auto It = InstrProfileMap.find(FName);
496     if (FS.getHeadSamples() > ColdSampleThreshold &&
497         It != InstrProfileMap.end() &&
498         It->second.MaxCount <= ColdInstrThreshold &&
499         FS.getBodySamples().size() >= SupplMinSizeThreshold) {
500       updateInstrProfileEntry(It->second, HotInstrThreshold,
501                               ZeroCounterThreshold);
502     }
503   }
504 }
505 
506 /// The main function to supplement instr profile with sample profile.
507 /// \Inputs contains the instr profile. \p SampleFilename specifies the
508 /// sample profile. \p OutputFilename specifies the output profile name.
509 /// \p OutputFormat specifies the output profile format. \p OutputSparse
510 /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
511 /// specifies the minimal size for the functions whose profile will be
512 /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
513 /// a function contains too many zero counters and whether its profile
514 /// should be dropped. \p InstrProfColdThreshold is the user specified
515 /// cold threshold which will override the cold threshold got from the
516 /// instr profile summary.
517 static void supplementInstrProfile(
518     const WeightedFileVector &Inputs, StringRef SampleFilename,
519     StringRef OutputFilename, ProfileFormat OutputFormat, bool OutputSparse,
520     unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
521     unsigned InstrProfColdThreshold) {
522   if (OutputFilename.compare("-") == 0)
523     exitWithError("Cannot write indexed profdata format to stdout.");
524   if (Inputs.size() != 1)
525     exitWithError("Expect one input to be an instr profile.");
526   if (Inputs[0].Weight != 1)
527     exitWithError("Expect instr profile doesn't have weight.");
528 
529   StringRef InstrFilename = Inputs[0].Filename;
530 
531   // Read sample profile.
532   LLVMContext Context;
533   auto ReaderOrErr =
534       sampleprof::SampleProfileReader::create(SampleFilename.str(), Context);
535   if (std::error_code EC = ReaderOrErr.getError())
536     exitWithErrorCode(EC, SampleFilename);
537   auto Reader = std::move(ReaderOrErr.get());
538   if (std::error_code EC = Reader->read())
539     exitWithErrorCode(EC, SampleFilename);
540 
541   // Read instr profile.
542   std::mutex ErrorLock;
543   SmallSet<instrprof_error, 4> WriterErrorCodes;
544   auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
545                                             WriterErrorCodes);
546   loadInput(Inputs[0], nullptr, WC.get());
547   if (WC->Errors.size() > 0)
548     exitWithError(std::move(WC->Errors[0].first), InstrFilename);
549 
550   adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
551                      InstrProfColdThreshold);
552   writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
553 }
554 
555 /// Make a copy of the given function samples with all symbol names remapped
556 /// by the provided symbol remapper.
557 static sampleprof::FunctionSamples
558 remapSamples(const sampleprof::FunctionSamples &Samples,
559              SymbolRemapper &Remapper, sampleprof_error &Error) {
560   sampleprof::FunctionSamples Result;
561   Result.setName(Remapper(Samples.getName()));
562   Result.addTotalSamples(Samples.getTotalSamples());
563   Result.addHeadSamples(Samples.getHeadSamples());
564   for (const auto &BodySample : Samples.getBodySamples()) {
565     Result.addBodySamples(BodySample.first.LineOffset,
566                           BodySample.first.Discriminator,
567                           BodySample.second.getSamples());
568     for (const auto &Target : BodySample.second.getCallTargets()) {
569       Result.addCalledTargetSamples(BodySample.first.LineOffset,
570                                     BodySample.first.Discriminator,
571                                     Remapper(Target.first()), Target.second);
572     }
573   }
574   for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
575     sampleprof::FunctionSamplesMap &Target =
576         Result.functionSamplesAt(CallsiteSamples.first);
577     for (const auto &Callsite : CallsiteSamples.second) {
578       sampleprof::FunctionSamples Remapped =
579           remapSamples(Callsite.second, Remapper, Error);
580       MergeResult(Error,
581                   Target[std::string(Remapped.getName())].merge(Remapped));
582     }
583   }
584   return Result;
585 }
586 
587 static sampleprof::SampleProfileFormat FormatMap[] = {
588     sampleprof::SPF_None,
589     sampleprof::SPF_Text,
590     sampleprof::SPF_Compact_Binary,
591     sampleprof::SPF_Ext_Binary,
592     sampleprof::SPF_GCC,
593     sampleprof::SPF_Binary};
594 
595 static std::unique_ptr<MemoryBuffer>
596 getInputFileBuf(const StringRef &InputFile) {
597   if (InputFile == "")
598     return {};
599 
600   auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
601   if (!BufOrError)
602     exitWithErrorCode(BufOrError.getError(), InputFile);
603 
604   return std::move(*BufOrError);
605 }
606 
607 static void populateProfileSymbolList(MemoryBuffer *Buffer,
608                                       sampleprof::ProfileSymbolList &PSL) {
609   if (!Buffer)
610     return;
611 
612   SmallVector<StringRef, 32> SymbolVec;
613   StringRef Data = Buffer->getBuffer();
614   Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
615 
616   for (StringRef symbol : SymbolVec)
617     PSL.add(symbol);
618 }
619 
620 static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
621                                   ProfileFormat OutputFormat,
622                                   MemoryBuffer *Buffer,
623                                   sampleprof::ProfileSymbolList &WriterList,
624                                   bool CompressAllSections, bool UseMD5,
625                                   bool GenPartialProfile) {
626   populateProfileSymbolList(Buffer, WriterList);
627   if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
628     warn("Profile Symbol list is not empty but the output format is not "
629          "ExtBinary format. The list will be lost in the output. ");
630 
631   Writer.setProfileSymbolList(&WriterList);
632 
633   if (CompressAllSections) {
634     if (OutputFormat != PF_Ext_Binary)
635       warn("-compress-all-section is ignored. Specify -extbinary to enable it");
636     else
637       Writer.setToCompressAllSections();
638   }
639   if (UseMD5) {
640     if (OutputFormat != PF_Ext_Binary)
641       warn("-use-md5 is ignored. Specify -extbinary to enable it");
642     else
643       Writer.setUseMD5();
644   }
645   if (GenPartialProfile) {
646     if (OutputFormat != PF_Ext_Binary)
647       warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
648     else
649       Writer.setPartialProfile();
650   }
651 }
652 
653 static void
654 mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
655                    StringRef OutputFilename, ProfileFormat OutputFormat,
656                    StringRef ProfileSymbolListFile, bool CompressAllSections,
657                    bool UseMD5, bool GenPartialProfile, FailureMode FailMode) {
658   using namespace sampleprof;
659   StringMap<FunctionSamples> ProfileMap;
660   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
661   LLVMContext Context;
662   sampleprof::ProfileSymbolList WriterList;
663   for (const auto &Input : Inputs) {
664     auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
665     if (std::error_code EC = ReaderOrErr.getError()) {
666       warnOrExitGivenError(FailMode, EC, Input.Filename);
667       continue;
668     }
669 
670     // We need to keep the readers around until after all the files are
671     // read so that we do not lose the function names stored in each
672     // reader's memory. The function names are needed to write out the
673     // merged profile map.
674     Readers.push_back(std::move(ReaderOrErr.get()));
675     const auto Reader = Readers.back().get();
676     if (std::error_code EC = Reader->read()) {
677       warnOrExitGivenError(FailMode, EC, Input.Filename);
678       Readers.pop_back();
679       continue;
680     }
681 
682     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
683     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
684                                               E = Profiles.end();
685          I != E; ++I) {
686       sampleprof_error Result = sampleprof_error::success;
687       FunctionSamples Remapped =
688           Remapper ? remapSamples(I->second, *Remapper, Result)
689                    : FunctionSamples();
690       FunctionSamples &Samples = Remapper ? Remapped : I->second;
691       StringRef FName = Samples.getName();
692       MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
693       if (Result != sampleprof_error::success) {
694         std::error_code EC = make_error_code(Result);
695         handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
696       }
697     }
698 
699     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
700         Reader->getProfileSymbolList();
701     if (ReaderList)
702       WriterList.merge(*ReaderList);
703   }
704   auto WriterOrErr =
705       SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
706   if (std::error_code EC = WriterOrErr.getError())
707     exitWithErrorCode(EC, OutputFilename);
708 
709   auto Writer = std::move(WriterOrErr.get());
710   // WriterList will have StringRef refering to string in Buffer.
711   // Make sure Buffer lives as long as WriterList.
712   auto Buffer = getInputFileBuf(ProfileSymbolListFile);
713   handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
714                         CompressAllSections, UseMD5, GenPartialProfile);
715   Writer->write(ProfileMap);
716 }
717 
718 static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
719   StringRef WeightStr, FileName;
720   std::tie(WeightStr, FileName) = WeightedFilename.split(',');
721 
722   uint64_t Weight;
723   if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
724     exitWithError("Input weight must be a positive integer.");
725 
726   return {std::string(FileName), Weight};
727 }
728 
729 static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
730   StringRef Filename = WF.Filename;
731   uint64_t Weight = WF.Weight;
732 
733   // If it's STDIN just pass it on.
734   if (Filename == "-") {
735     WNI.push_back({std::string(Filename), Weight});
736     return;
737   }
738 
739   llvm::sys::fs::file_status Status;
740   llvm::sys::fs::status(Filename, Status);
741   if (!llvm::sys::fs::exists(Status))
742     exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
743                       Filename);
744   // If it's a source file, collect it.
745   if (llvm::sys::fs::is_regular_file(Status)) {
746     WNI.push_back({std::string(Filename), Weight});
747     return;
748   }
749 
750   if (llvm::sys::fs::is_directory(Status)) {
751     std::error_code EC;
752     for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
753          F != E && !EC; F.increment(EC)) {
754       if (llvm::sys::fs::is_regular_file(F->path())) {
755         addWeightedInput(WNI, {F->path(), Weight});
756       }
757     }
758     if (EC)
759       exitWithErrorCode(EC, Filename);
760   }
761 }
762 
763 static void parseInputFilenamesFile(MemoryBuffer *Buffer,
764                                     WeightedFileVector &WFV) {
765   if (!Buffer)
766     return;
767 
768   SmallVector<StringRef, 8> Entries;
769   StringRef Data = Buffer->getBuffer();
770   Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
771   for (const StringRef &FileWeightEntry : Entries) {
772     StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
773     // Skip comments.
774     if (SanitizedEntry.startswith("#"))
775       continue;
776     // If there's no comma, it's an unweighted profile.
777     else if (SanitizedEntry.find(',') == StringRef::npos)
778       addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
779     else
780       addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
781   }
782 }
783 
784 static int merge_main(int argc, const char *argv[]) {
785   cl::list<std::string> InputFilenames(cl::Positional,
786                                        cl::desc("<filename...>"));
787   cl::list<std::string> WeightedInputFilenames("weighted-input",
788                                                cl::desc("<weight>,<filename>"));
789   cl::opt<std::string> InputFilenamesFile(
790       "input-files", cl::init(""),
791       cl::desc("Path to file containing newline-separated "
792                "[<weight>,]<filename> entries"));
793   cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
794                                 cl::aliasopt(InputFilenamesFile));
795   cl::opt<bool> DumpInputFileList(
796       "dump-input-file-list", cl::init(false), cl::Hidden,
797       cl::desc("Dump the list of input files and their weights, then exit"));
798   cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
799                                      cl::desc("Symbol remapping file"));
800   cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
801                            cl::aliasopt(RemappingFile));
802   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
803                                       cl::init("-"), cl::Required,
804                                       cl::desc("Output file"));
805   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
806                             cl::aliasopt(OutputFilename));
807   cl::opt<ProfileKinds> ProfileKind(
808       cl::desc("Profile kind:"), cl::init(instr),
809       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
810                  clEnumVal(sample, "Sample profile")));
811   cl::opt<ProfileFormat> OutputFormat(
812       cl::desc("Format of output profile"), cl::init(PF_Binary),
813       cl::values(
814           clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
815           clEnumValN(PF_Compact_Binary, "compbinary",
816                      "Compact binary encoding"),
817           clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
818           clEnumValN(PF_Text, "text", "Text encoding"),
819           clEnumValN(PF_GCC, "gcc",
820                      "GCC encoding (only meaningful for -sample)")));
821   cl::opt<FailureMode> FailureMode(
822       "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
823       cl::values(clEnumValN(failIfAnyAreInvalid, "any",
824                             "Fail if any profile is invalid."),
825                  clEnumValN(failIfAllAreInvalid, "all",
826                             "Fail only if all profiles are invalid.")));
827   cl::opt<bool> OutputSparse("sparse", cl::init(false),
828       cl::desc("Generate a sparse profile (only meaningful for -instr)"));
829   cl::opt<unsigned> NumThreads(
830       "num-threads", cl::init(0),
831       cl::desc("Number of merge threads to use (default: autodetect)"));
832   cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
833                         cl::aliasopt(NumThreads));
834   cl::opt<std::string> ProfileSymbolListFile(
835       "prof-sym-list", cl::init(""),
836       cl::desc("Path to file containing the list of function symbols "
837                "used to populate profile symbol list"));
838   cl::opt<bool> CompressAllSections(
839       "compress-all-sections", cl::init(false), cl::Hidden,
840       cl::desc("Compress all sections when writing the profile (only "
841                "meaningful for -extbinary)"));
842   cl::opt<bool> UseMD5(
843       "use-md5", cl::init(false), cl::Hidden,
844       cl::desc("Choose to use MD5 to represent string in name table (only "
845                "meaningful for -extbinary)"));
846   cl::opt<bool> GenPartialProfile(
847       "gen-partial-profile", cl::init(false), cl::Hidden,
848       cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
849   cl::opt<std::string> SupplInstrWithSample(
850       "supplement-instr-with-sample", cl::init(""), cl::Hidden,
851       cl::desc("Supplement an instr profile with sample profile, to correct "
852                "the profile unrepresentativeness issue. The sample "
853                "profile is the input of the flag. Output will be in instr "
854                "format (The flag only works with -instr)"));
855   cl::opt<float> ZeroCounterThreshold(
856       "zero-counter-threshold", cl::init(0.7), cl::Hidden,
857       cl::desc("For the function which is cold in instr profile but hot in "
858                "sample profile, if the ratio of the number of zero counters "
859                "divided by the the total number of counters is above the "
860                "threshold, the profile of the function will be regarded as "
861                "being harmful for performance and will be dropped. "));
862   cl::opt<unsigned> SupplMinSizeThreshold(
863       "suppl-min-size-threshold", cl::init(10), cl::Hidden,
864       cl::desc("If the size of a function is smaller than the threshold, "
865                "assume it can be inlined by PGO early inliner and it won't "
866                "be adjusted based on sample profile. "));
867   cl::opt<unsigned> InstrProfColdThreshold(
868       "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
869       cl::desc("User specified cold threshold for instr profile which will "
870                "override the cold threshold got from profile summary. "));
871 
872   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
873 
874   WeightedFileVector WeightedInputs;
875   for (StringRef Filename : InputFilenames)
876     addWeightedInput(WeightedInputs, {std::string(Filename), 1});
877   for (StringRef WeightedFilename : WeightedInputFilenames)
878     addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
879 
880   // Make sure that the file buffer stays alive for the duration of the
881   // weighted input vector's lifetime.
882   auto Buffer = getInputFileBuf(InputFilenamesFile);
883   parseInputFilenamesFile(Buffer.get(), WeightedInputs);
884 
885   if (WeightedInputs.empty())
886     exitWithError("No input files specified. See " +
887                   sys::path::filename(argv[0]) + " -help");
888 
889   if (DumpInputFileList) {
890     for (auto &WF : WeightedInputs)
891       outs() << WF.Weight << "," << WF.Filename << "\n";
892     return 0;
893   }
894 
895   std::unique_ptr<SymbolRemapper> Remapper;
896   if (!RemappingFile.empty())
897     Remapper = SymbolRemapper::create(RemappingFile);
898 
899   if (!SupplInstrWithSample.empty()) {
900     if (ProfileKind != instr)
901       exitWithError(
902           "-supplement-instr-with-sample can only work with -instr. ");
903 
904     supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputFilename,
905                            OutputFormat, OutputSparse, SupplMinSizeThreshold,
906                            ZeroCounterThreshold, InstrProfColdThreshold);
907     return 0;
908   }
909 
910   if (ProfileKind == instr)
911     mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
912                       OutputFormat, OutputSparse, NumThreads, FailureMode);
913   else
914     mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
915                        OutputFormat, ProfileSymbolListFile, CompressAllSections,
916                        UseMD5, GenPartialProfile, FailureMode);
917 
918   return 0;
919 }
920 
921 /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
922 static void overlapInstrProfile(const std::string &BaseFilename,
923                                 const std::string &TestFilename,
924                                 const OverlapFuncFilters &FuncFilter,
925                                 raw_fd_ostream &OS, bool IsCS) {
926   std::mutex ErrorLock;
927   SmallSet<instrprof_error, 4> WriterErrorCodes;
928   WriterContext Context(false, ErrorLock, WriterErrorCodes);
929   WeightedFile WeightedInput{BaseFilename, 1};
930   OverlapStats Overlap;
931   Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
932   if (E)
933     exitWithError(std::move(E), "Error in getting profile count sums");
934   if (Overlap.Base.CountSum < 1.0f) {
935     OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
936     exit(0);
937   }
938   if (Overlap.Test.CountSum < 1.0f) {
939     OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
940     exit(0);
941   }
942   loadInput(WeightedInput, nullptr, &Context);
943   overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
944                IsCS);
945   Overlap.dump(OS);
946 }
947 
948 static int overlap_main(int argc, const char *argv[]) {
949   cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
950                                     cl::desc("<base profile file>"));
951   cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
952                                     cl::desc("<test profile file>"));
953   cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
954                               cl::desc("Output file"));
955   cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
956   cl::opt<bool> IsCS("cs", cl::init(false),
957                      cl::desc("For context sensitive counts"));
958   cl::opt<unsigned long long> ValueCutoff(
959       "value-cutoff", cl::init(-1),
960       cl::desc(
961           "Function level overlap information for every function in test "
962           "profile with max count value greater then the parameter value"));
963   cl::opt<std::string> FuncNameFilter(
964       "function",
965       cl::desc("Function level overlap information for matching functions"));
966   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
967 
968   std::error_code EC;
969   raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
970   if (EC)
971     exitWithErrorCode(EC, Output);
972 
973   overlapInstrProfile(BaseFilename, TestFilename,
974                       OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
975                       IsCS);
976 
977   return 0;
978 }
979 
980 typedef struct ValueSitesStats {
981   ValueSitesStats()
982       : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
983         TotalNumValues(0) {}
984   uint64_t TotalNumValueSites;
985   uint64_t TotalNumValueSitesWithValueProfile;
986   uint64_t TotalNumValues;
987   std::vector<unsigned> ValueSitesHistogram;
988 } ValueSitesStats;
989 
990 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
991                                   ValueSitesStats &Stats, raw_fd_ostream &OS,
992                                   InstrProfSymtab *Symtab) {
993   uint32_t NS = Func.getNumValueSites(VK);
994   Stats.TotalNumValueSites += NS;
995   for (size_t I = 0; I < NS; ++I) {
996     uint32_t NV = Func.getNumValueDataForSite(VK, I);
997     std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
998     Stats.TotalNumValues += NV;
999     if (NV) {
1000       Stats.TotalNumValueSitesWithValueProfile++;
1001       if (NV > Stats.ValueSitesHistogram.size())
1002         Stats.ValueSitesHistogram.resize(NV, 0);
1003       Stats.ValueSitesHistogram[NV - 1]++;
1004     }
1005 
1006     uint64_t SiteSum = 0;
1007     for (uint32_t V = 0; V < NV; V++)
1008       SiteSum += VD[V].Count;
1009     if (SiteSum == 0)
1010       SiteSum = 1;
1011 
1012     for (uint32_t V = 0; V < NV; V++) {
1013       OS << "\t[ " << format("%2u", I) << ", ";
1014       if (Symtab == nullptr)
1015         OS << format("%4" PRIu64, VD[V].Value);
1016       else
1017         OS << Symtab->getFuncName(VD[V].Value);
1018       OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
1019          << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
1020     }
1021   }
1022 }
1023 
1024 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
1025                                 ValueSitesStats &Stats) {
1026   OS << "  Total number of sites: " << Stats.TotalNumValueSites << "\n";
1027   OS << "  Total number of sites with values: "
1028      << Stats.TotalNumValueSitesWithValueProfile << "\n";
1029   OS << "  Total number of profiled values: " << Stats.TotalNumValues << "\n";
1030 
1031   OS << "  Value sites histogram:\n\tNumTargets, SiteCount\n";
1032   for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
1033     if (Stats.ValueSitesHistogram[I] > 0)
1034       OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
1035   }
1036 }
1037 
1038 static int showInstrProfile(const std::string &Filename, bool ShowCounts,
1039                             uint32_t TopN, bool ShowIndirectCallTargets,
1040                             bool ShowMemOPSizes, bool ShowDetailedSummary,
1041                             std::vector<uint32_t> DetailedSummaryCutoffs,
1042                             bool ShowAllFunctions, bool ShowCS,
1043                             uint64_t ValueCutoff, bool OnlyListBelow,
1044                             const std::string &ShowFunction, bool TextFormat,
1045                             raw_fd_ostream &OS) {
1046   auto ReaderOrErr = InstrProfReader::create(Filename);
1047   std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
1048   if (ShowDetailedSummary && Cutoffs.empty()) {
1049     Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
1050   }
1051   InstrProfSummaryBuilder Builder(std::move(Cutoffs));
1052   if (Error E = ReaderOrErr.takeError())
1053     exitWithError(std::move(E), Filename);
1054 
1055   auto Reader = std::move(ReaderOrErr.get());
1056   bool IsIRInstr = Reader->isIRLevelProfile();
1057   size_t ShownFunctions = 0;
1058   size_t BelowCutoffFunctions = 0;
1059   int NumVPKind = IPVK_Last - IPVK_First + 1;
1060   std::vector<ValueSitesStats> VPStats(NumVPKind);
1061 
1062   auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
1063                    const std::pair<std::string, uint64_t> &v2) {
1064     return v1.second > v2.second;
1065   };
1066 
1067   std::priority_queue<std::pair<std::string, uint64_t>,
1068                       std::vector<std::pair<std::string, uint64_t>>,
1069                       decltype(MinCmp)>
1070       HottestFuncs(MinCmp);
1071 
1072   if (!TextFormat && OnlyListBelow) {
1073     OS << "The list of functions with the maximum counter less than "
1074        << ValueCutoff << ":\n";
1075   }
1076 
1077   // Add marker so that IR-level instrumentation round-trips properly.
1078   if (TextFormat && IsIRInstr)
1079     OS << ":ir\n";
1080 
1081   for (const auto &Func : *Reader) {
1082     if (Reader->isIRLevelProfile()) {
1083       bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
1084       if (FuncIsCS != ShowCS)
1085         continue;
1086     }
1087     bool Show =
1088         ShowAllFunctions || (!ShowFunction.empty() &&
1089                              Func.Name.find(ShowFunction) != Func.Name.npos);
1090 
1091     bool doTextFormatDump = (Show && TextFormat);
1092 
1093     if (doTextFormatDump) {
1094       InstrProfSymtab &Symtab = Reader->getSymtab();
1095       InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
1096                                          OS);
1097       continue;
1098     }
1099 
1100     assert(Func.Counts.size() > 0 && "function missing entry counter");
1101     Builder.addRecord(Func);
1102 
1103     uint64_t FuncMax = 0;
1104     uint64_t FuncSum = 0;
1105     for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
1106       if (Func.Counts[I] == (uint64_t)-1)
1107         continue;
1108       FuncMax = std::max(FuncMax, Func.Counts[I]);
1109       FuncSum += Func.Counts[I];
1110     }
1111 
1112     if (FuncMax < ValueCutoff) {
1113       ++BelowCutoffFunctions;
1114       if (OnlyListBelow) {
1115         OS << "  " << Func.Name << ": (Max = " << FuncMax
1116            << " Sum = " << FuncSum << ")\n";
1117       }
1118       continue;
1119     } else if (OnlyListBelow)
1120       continue;
1121 
1122     if (TopN) {
1123       if (HottestFuncs.size() == TopN) {
1124         if (HottestFuncs.top().second < FuncMax) {
1125           HottestFuncs.pop();
1126           HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
1127         }
1128       } else
1129         HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
1130     }
1131 
1132     if (Show) {
1133       if (!ShownFunctions)
1134         OS << "Counters:\n";
1135 
1136       ++ShownFunctions;
1137 
1138       OS << "  " << Func.Name << ":\n"
1139          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
1140          << "    Counters: " << Func.Counts.size() << "\n";
1141       if (!IsIRInstr)
1142         OS << "    Function count: " << Func.Counts[0] << "\n";
1143 
1144       if (ShowIndirectCallTargets)
1145         OS << "    Indirect Call Site Count: "
1146            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
1147 
1148       uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
1149       if (ShowMemOPSizes && NumMemOPCalls > 0)
1150         OS << "    Number of Memory Intrinsics Calls: " << NumMemOPCalls
1151            << "\n";
1152 
1153       if (ShowCounts) {
1154         OS << "    Block counts: [";
1155         size_t Start = (IsIRInstr ? 0 : 1);
1156         for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
1157           OS << (I == Start ? "" : ", ") << Func.Counts[I];
1158         }
1159         OS << "]\n";
1160       }
1161 
1162       if (ShowIndirectCallTargets) {
1163         OS << "    Indirect Target Results:\n";
1164         traverseAllValueSites(Func, IPVK_IndirectCallTarget,
1165                               VPStats[IPVK_IndirectCallTarget], OS,
1166                               &(Reader->getSymtab()));
1167       }
1168 
1169       if (ShowMemOPSizes && NumMemOPCalls > 0) {
1170         OS << "    Memory Intrinsic Size Results:\n";
1171         traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
1172                               nullptr);
1173       }
1174     }
1175   }
1176   if (Reader->hasError())
1177     exitWithError(Reader->getError(), Filename);
1178 
1179   if (TextFormat)
1180     return 0;
1181   std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
1182   bool IsIR = Reader->isIRLevelProfile();
1183   OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
1184   if (IsIR)
1185     OS << "  entry_first = " << Reader->instrEntryBBEnabled();
1186   OS << "\n";
1187   if (ShowAllFunctions || !ShowFunction.empty())
1188     OS << "Functions shown: " << ShownFunctions << "\n";
1189   OS << "Total functions: " << PS->getNumFunctions() << "\n";
1190   if (ValueCutoff > 0) {
1191     OS << "Number of functions with maximum count (< " << ValueCutoff
1192        << "): " << BelowCutoffFunctions << "\n";
1193     OS << "Number of functions with maximum count (>= " << ValueCutoff
1194        << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
1195   }
1196   OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
1197   OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
1198 
1199   if (TopN) {
1200     std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
1201     while (!HottestFuncs.empty()) {
1202       SortedHottestFuncs.emplace_back(HottestFuncs.top());
1203       HottestFuncs.pop();
1204     }
1205     OS << "Top " << TopN
1206        << " functions with the largest internal block counts: \n";
1207     for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
1208       OS << "  " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
1209   }
1210 
1211   if (ShownFunctions && ShowIndirectCallTargets) {
1212     OS << "Statistics for indirect call sites profile:\n";
1213     showValueSitesStats(OS, IPVK_IndirectCallTarget,
1214                         VPStats[IPVK_IndirectCallTarget]);
1215   }
1216 
1217   if (ShownFunctions && ShowMemOPSizes) {
1218     OS << "Statistics for memory intrinsic calls sizes profile:\n";
1219     showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
1220   }
1221 
1222   if (ShowDetailedSummary) {
1223     OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
1224     OS << "Total count: " << PS->getTotalCount() << "\n";
1225     PS->printDetailedSummary(OS);
1226   }
1227   return 0;
1228 }
1229 
1230 static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
1231                             raw_fd_ostream &OS) {
1232   if (!Reader->dumpSectionInfo(OS)) {
1233     WithColor::warning() << "-show-sec-info-only is only supported for "
1234                          << "sample profile in extbinary format and is "
1235                          << "ignored for other formats.\n";
1236     return;
1237   }
1238 }
1239 
1240 namespace {
1241 struct HotFuncInfo {
1242   StringRef FuncName;
1243   uint64_t TotalCount;
1244   double TotalCountPercent;
1245   uint64_t MaxCount;
1246   uint64_t EntryCount;
1247 
1248   HotFuncInfo()
1249       : FuncName(), TotalCount(0), TotalCountPercent(0.0f), MaxCount(0),
1250         EntryCount(0) {}
1251 
1252   HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
1253       : FuncName(FN), TotalCount(TS), TotalCountPercent(TSP), MaxCount(MS),
1254         EntryCount(ES) {}
1255 };
1256 } // namespace
1257 
1258 // Print out detailed information about hot functions in PrintValues vector.
1259 // Users specify titles and offset of every columns through ColumnTitle and
1260 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
1261 // and at least 4. Besides, users can optionally give a HotFuncMetric string to
1262 // print out or let it be an empty string.
1263 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
1264                                 const std::vector<int> &ColumnOffset,
1265                                 const std::vector<HotFuncInfo> &PrintValues,
1266                                 uint64_t HotFuncCount, uint64_t TotalFuncCount,
1267                                 uint64_t HotProfCount, uint64_t TotalProfCount,
1268                                 const std::string &HotFuncMetric,
1269                                 raw_fd_ostream &OS) {
1270   assert(ColumnOffset.size() == ColumnTitle.size());
1271   assert(ColumnTitle.size() >= 4);
1272   assert(TotalFuncCount > 0);
1273   double TotalProfPercent = 0;
1274   if (TotalProfCount > 0)
1275     TotalProfPercent = ((double)HotProfCount) / TotalProfCount * 100;
1276 
1277   formatted_raw_ostream FOS(OS);
1278   FOS << HotFuncCount << " out of " << TotalFuncCount
1279       << " functions with profile ("
1280       << format("%.2f%%", (((double)HotFuncCount) / TotalFuncCount * 100))
1281       << ") are considered hot functions";
1282   if (!HotFuncMetric.empty())
1283     FOS << " (" << HotFuncMetric << ")";
1284   FOS << ".\n";
1285   FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
1286       << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
1287 
1288   for (size_t I = 0; I < ColumnTitle.size(); ++I) {
1289     FOS.PadToColumn(ColumnOffset[I]);
1290     FOS << ColumnTitle[I];
1291   }
1292   FOS << "\n";
1293 
1294   for (const HotFuncInfo &R : PrintValues) {
1295     FOS.PadToColumn(ColumnOffset[0]);
1296     FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
1297     FOS.PadToColumn(ColumnOffset[1]);
1298     FOS << R.MaxCount;
1299     FOS.PadToColumn(ColumnOffset[2]);
1300     FOS << R.EntryCount;
1301     FOS.PadToColumn(ColumnOffset[3]);
1302     FOS << R.FuncName << "\n";
1303   }
1304   return;
1305 }
1306 
1307 static int
1308 showHotFunctionList(const StringMap<sampleprof::FunctionSamples> &Profiles,
1309                     ProfileSummary &PS, raw_fd_ostream &OS) {
1310   using namespace sampleprof;
1311 
1312   const uint32_t HotFuncCutoff = 990000;
1313   auto &SummaryVector = PS.getDetailedSummary();
1314   uint64_t MinCountThreshold = 0;
1315   for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
1316     if (SummaryEntry.Cutoff == HotFuncCutoff) {
1317       MinCountThreshold = SummaryEntry.MinCount;
1318       break;
1319     }
1320   }
1321   assert(MinCountThreshold != 0);
1322 
1323   // Traverse all functions in the profile and keep only hot functions.
1324   // The following loop also calculates the sum of total samples of all
1325   // functions.
1326   std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
1327                 std::greater<uint64_t>>
1328       HotFunc;
1329   uint64_t ProfileTotalSample = 0;
1330   uint64_t HotFuncSample = 0;
1331   uint64_t HotFuncCount = 0;
1332   uint64_t MaxCount = 0;
1333   for (const auto &I : Profiles) {
1334     const FunctionSamples &FuncProf = I.second;
1335     ProfileTotalSample += FuncProf.getTotalSamples();
1336     MaxCount = FuncProf.getMaxCountInside();
1337 
1338     // MinCountThreshold is a block/line threshold computed for a given cutoff.
1339     // We intentionally compare the maximum sample count in a function with this
1340     // threshold to get an approximate threshold for hot functions.
1341     if (MaxCount >= MinCountThreshold) {
1342       HotFunc.emplace(FuncProf.getTotalSamples(),
1343                       std::make_pair(&(I.second), MaxCount));
1344       HotFuncSample += FuncProf.getTotalSamples();
1345       ++HotFuncCount;
1346     }
1347   }
1348 
1349   std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
1350                                        "Entry sample", "Function name"};
1351   std::vector<int> ColumnOffset{0, 24, 42, 58};
1352   std::string Metric =
1353       std::string("max sample >= ") + std::to_string(MinCountThreshold);
1354   std::vector<HotFuncInfo> PrintValues;
1355   for (const auto &FuncPair : HotFunc) {
1356     const FunctionSamples &Func = *FuncPair.second.first;
1357     double TotalSamplePercent =
1358         (ProfileTotalSample > 0)
1359             ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
1360             : 0;
1361     PrintValues.emplace_back(HotFuncInfo(
1362         Func.getFuncName(), Func.getTotalSamples(), TotalSamplePercent,
1363         FuncPair.second.second, Func.getEntrySamples()));
1364   }
1365   dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
1366                       Profiles.size(), HotFuncSample, ProfileTotalSample,
1367                       Metric, OS);
1368 
1369   return 0;
1370 }
1371 
1372 static int showSampleProfile(const std::string &Filename, bool ShowCounts,
1373                              bool ShowAllFunctions, bool ShowDetailedSummary,
1374                              const std::string &ShowFunction,
1375                              bool ShowProfileSymbolList,
1376                              bool ShowSectionInfoOnly, bool ShowHotFuncList,
1377                              raw_fd_ostream &OS) {
1378   using namespace sampleprof;
1379   LLVMContext Context;
1380   auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
1381   if (std::error_code EC = ReaderOrErr.getError())
1382     exitWithErrorCode(EC, Filename);
1383 
1384   auto Reader = std::move(ReaderOrErr.get());
1385 
1386   if (ShowSectionInfoOnly) {
1387     showSectionInfo(Reader.get(), OS);
1388     return 0;
1389   }
1390 
1391   if (std::error_code EC = Reader->read())
1392     exitWithErrorCode(EC, Filename);
1393 
1394   if (ShowAllFunctions || ShowFunction.empty())
1395     Reader->dump(OS);
1396   else
1397     Reader->dumpFunctionProfile(ShowFunction, OS);
1398 
1399   if (ShowProfileSymbolList) {
1400     std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
1401         Reader->getProfileSymbolList();
1402     ReaderList->dump(OS);
1403   }
1404 
1405   if (ShowDetailedSummary) {
1406     auto &PS = Reader->getSummary();
1407     PS.printSummary(OS);
1408     PS.printDetailedSummary(OS);
1409   }
1410 
1411   if (ShowHotFuncList)
1412     showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), OS);
1413 
1414   return 0;
1415 }
1416 
1417 static int show_main(int argc, const char *argv[]) {
1418   cl::opt<std::string> Filename(cl::Positional, cl::Required,
1419                                 cl::desc("<profdata-file>"));
1420 
1421   cl::opt<bool> ShowCounts("counts", cl::init(false),
1422                            cl::desc("Show counter values for shown functions"));
1423   cl::opt<bool> TextFormat(
1424       "text", cl::init(false),
1425       cl::desc("Show instr profile data in text dump format"));
1426   cl::opt<bool> ShowIndirectCallTargets(
1427       "ic-targets", cl::init(false),
1428       cl::desc("Show indirect call site target values for shown functions"));
1429   cl::opt<bool> ShowMemOPSizes(
1430       "memop-sizes", cl::init(false),
1431       cl::desc("Show the profiled sizes of the memory intrinsic calls "
1432                "for shown functions"));
1433   cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
1434                                     cl::desc("Show detailed profile summary"));
1435   cl::list<uint32_t> DetailedSummaryCutoffs(
1436       cl::CommaSeparated, "detailed-summary-cutoffs",
1437       cl::desc(
1438           "Cutoff percentages (times 10000) for generating detailed summary"),
1439       cl::value_desc("800000,901000,999999"));
1440   cl::opt<bool> ShowHotFuncList(
1441       "hot-func-list", cl::init(false),
1442       cl::desc("Show profile summary of a list of hot functions"));
1443   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
1444                                  cl::desc("Details for every function"));
1445   cl::opt<bool> ShowCS("showcs", cl::init(false),
1446                        cl::desc("Show context sensitive counts"));
1447   cl::opt<std::string> ShowFunction("function",
1448                                     cl::desc("Details for matching functions"));
1449 
1450   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
1451                                       cl::init("-"), cl::desc("Output file"));
1452   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
1453                             cl::aliasopt(OutputFilename));
1454   cl::opt<ProfileKinds> ProfileKind(
1455       cl::desc("Profile kind:"), cl::init(instr),
1456       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
1457                  clEnumVal(sample, "Sample profile")));
1458   cl::opt<uint32_t> TopNFunctions(
1459       "topn", cl::init(0),
1460       cl::desc("Show the list of functions with the largest internal counts"));
1461   cl::opt<uint32_t> ValueCutoff(
1462       "value-cutoff", cl::init(0),
1463       cl::desc("Set the count value cutoff. Functions with the maximum count "
1464                "less than this value will not be printed out. (Default is 0)"));
1465   cl::opt<bool> OnlyListBelow(
1466       "list-below-cutoff", cl::init(false),
1467       cl::desc("Only output names of functions whose max count values are "
1468                "below the cutoff value"));
1469   cl::opt<bool> ShowProfileSymbolList(
1470       "show-prof-sym-list", cl::init(false),
1471       cl::desc("Show profile symbol list if it exists in the profile. "));
1472   cl::opt<bool> ShowSectionInfoOnly(
1473       "show-sec-info-only", cl::init(false),
1474       cl::desc("Show the information of each section in the sample profile. "
1475                "The flag is only usable when the sample profile is in "
1476                "extbinary format"));
1477 
1478   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
1479 
1480   if (OutputFilename.empty())
1481     OutputFilename = "-";
1482 
1483   if (!Filename.compare(OutputFilename)) {
1484     errs() << sys::path::filename(argv[0])
1485            << ": Input file name cannot be the same as the output file name!\n";
1486     return 1;
1487   }
1488 
1489   std::error_code EC;
1490   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
1491   if (EC)
1492     exitWithErrorCode(EC, OutputFilename);
1493 
1494   if (ShowAllFunctions && !ShowFunction.empty())
1495     WithColor::warning() << "-function argument ignored: showing all functions\n";
1496 
1497   if (ProfileKind == instr)
1498     return showInstrProfile(Filename, ShowCounts, TopNFunctions,
1499                             ShowIndirectCallTargets, ShowMemOPSizes,
1500                             ShowDetailedSummary, DetailedSummaryCutoffs,
1501                             ShowAllFunctions, ShowCS, ValueCutoff,
1502                             OnlyListBelow, ShowFunction, TextFormat, OS);
1503   else
1504     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
1505                              ShowDetailedSummary, ShowFunction,
1506                              ShowProfileSymbolList, ShowSectionInfoOnly,
1507                              ShowHotFuncList, OS);
1508 }
1509 
1510 int main(int argc, const char *argv[]) {
1511   InitLLVM X(argc, argv);
1512 
1513   StringRef ProgName(sys::path::filename(argv[0]));
1514   if (argc > 1) {
1515     int (*func)(int, const char *[]) = nullptr;
1516 
1517     if (strcmp(argv[1], "merge") == 0)
1518       func = merge_main;
1519     else if (strcmp(argv[1], "show") == 0)
1520       func = show_main;
1521     else if (strcmp(argv[1], "overlap") == 0)
1522       func = overlap_main;
1523 
1524     if (func) {
1525       std::string Invocation(ProgName.str() + " " + argv[1]);
1526       argv[1] = Invocation.c_str();
1527       return func(argc - 1, argv + 1);
1528     }
1529 
1530     if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
1531         strcmp(argv[1], "--help") == 0) {
1532 
1533       errs() << "OVERVIEW: LLVM profile data tools\n\n"
1534              << "USAGE: " << ProgName << " <command> [args...]\n"
1535              << "USAGE: " << ProgName << " <command> -help\n\n"
1536              << "See each individual command --help for more details.\n"
1537              << "Available commands: merge, show, overlap\n";
1538       return 0;
1539     }
1540   }
1541 
1542   if (argc < 2)
1543     errs() << ProgName << ": No command specified!\n";
1544   else
1545     errs() << ProgName << ": Unknown command!\n";
1546 
1547   errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
1548   return 1;
1549 }
1550