1 //===-- PerfReader.cpp - perfscript reader  ---------------------*- C++ -*-===//
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 #include "PerfReader.h"
9 #include "ProfileGenerator.h"
10 #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h"
11 #include "llvm/Support/FileSystem.h"
12 #include "llvm/Support/Process.h"
13 
14 #define DEBUG_TYPE "perf-reader"
15 
16 cl::opt<bool> SkipSymbolization("skip-symbolization", cl::init(false),
17                                 cl::ZeroOrMore,
18                                 cl::desc("Dump the unsymbolized profile to the "
19                                          "output file. It will show unwinder "
20                                          "output for CS profile generation."));
21 
22 static cl::opt<bool> ShowMmapEvents("show-mmap-events", cl::init(false),
23                                     cl::ZeroOrMore,
24                                     cl::desc("Print binary load events."));
25 
26 static cl::opt<bool>
27     UseOffset("use-offset", cl::init(true), cl::ZeroOrMore,
28               cl::desc("Work with `--skip-symbolization` or "
29                        "`--unsymbolized-profile` to write/read the "
30                        "offset instead of virtual address."));
31 
32 static cl::opt<bool> UseLoadableSegmentAsBase(
33     "use-first-loadable-segment-as-base", cl::init(false), cl::ZeroOrMore,
34     cl::desc("Use first loadable segment address as base address "
35              "for offsets in unsymbolized profile. By default "
36              "first executable segment address is used"));
37 
38 static cl::opt<bool>
39     IgnoreStackSamples("ignore-stack-samples", cl::init(false), cl::ZeroOrMore,
40                        cl::desc("Ignore call stack samples for hybrid samples "
41                                 "and produce context-insensitive profile."));
42 cl::opt<bool> ShowDetailedWarning("show-detailed-warning", cl::init(false),
43                                   cl::ZeroOrMore,
44                                   cl::desc("Show detailed warning message."));
45 
46 extern cl::opt<std::string> PerfTraceFilename;
47 extern cl::opt<bool> ShowDisassemblyOnly;
48 extern cl::opt<bool> ShowSourceLocations;
49 extern cl::opt<std::string> OutputFilename;
50 
51 namespace llvm {
52 namespace sampleprof {
53 
54 void VirtualUnwinder::unwindCall(UnwindState &State) {
55   uint64_t Source = State.getCurrentLBRSource();
56   // An artificial return should push an external frame and an artificial call
57   // will match it and pop the external frame so that the context before and
58   // after the external call will be the same.
59   if (State.getCurrentLBR().IsArtificial) {
60     NumExtCallBranch++;
61     // A return is matched and pop the external frame.
62     if (State.getParentFrame()->isExternalFrame()) {
63       State.popFrame();
64     } else {
65       // An artificial return is missing, it happens that the sample is just hit
66       // in the middle of the external code. In this case, the leading branch is
67       // a call to external, we just keep unwinding use a context-less stack.
68       if (State.getParentFrame() != State.getDummyRootPtr())
69         NumMissingExternalFrame++;
70       State.clearCallStack();
71       State.pushFrame(Source);
72       State.InstPtr.update(Source);
73       return;
74     }
75   }
76 
77   auto *ParentFrame = State.getParentFrame();
78   // The 2nd frame after leaf could be missing if stack sample is
79   // taken when IP is within prolog/epilog, as frame chain isn't
80   // setup yet. Fill in the missing frame in that case.
81   // TODO: Currently we just assume all the addr that can't match the
82   // 2nd frame is in prolog/epilog. In the future, we will switch to
83   // pro/epi tracker(Dwarf CFI) for the precise check.
84   if (ParentFrame == State.getDummyRootPtr() ||
85       ParentFrame->Address != Source) {
86     State.switchToFrame(Source);
87     if (ParentFrame != State.getDummyRootPtr()) {
88       if (State.getCurrentLBR().IsArtificial)
89         NumMismatchedExtCallBranch++;
90       else
91         NumMismatchedProEpiBranch++;
92     }
93   } else {
94     State.popFrame();
95   }
96   State.InstPtr.update(Source);
97 }
98 
99 void VirtualUnwinder::unwindLinear(UnwindState &State, uint64_t Repeat) {
100   InstructionPointer &IP = State.InstPtr;
101   uint64_t Target = State.getCurrentLBRTarget();
102   uint64_t End = IP.Address;
103   if (Target > End) {
104     // Skip unwinding the rest of LBR trace when a bogus range is seen.
105     State.setInvalid();
106     return;
107   }
108   if (Binary->usePseudoProbes()) {
109     // We don't need to top frame probe since it should be extracted
110     // from the range.
111     // The outcome of the virtual unwinding with pseudo probes is a
112     // map from a context key to the address range being unwound.
113     // This means basically linear unwinding is not needed for pseudo
114     // probes. The range will be simply recorded here and will be
115     // converted to a list of pseudo probes to report in ProfileGenerator.
116     State.getParentFrame()->recordRangeCount(Target, End, Repeat);
117   } else {
118     // Unwind linear execution part.
119     // Split and record the range by different inline context. For example:
120     // [0x01] ... main:1          # Target
121     // [0x02] ... main:2
122     // [0x03] ... main:3 @ foo:1
123     // [0x04] ... main:3 @ foo:2
124     // [0x05] ... main:3 @ foo:3
125     // [0x06] ... main:4
126     // [0x07] ... main:5          # End
127     // It will be recorded:
128     // [main:*]         : [0x06, 0x07], [0x01, 0x02]
129     // [main:3 @ foo:*] : [0x03, 0x05]
130     while (IP.Address > Target) {
131       uint64_t PrevIP = IP.Address;
132       IP.backward();
133       // Break into segments for implicit call/return due to inlining
134       bool SameInlinee = Binary->inlineContextEqual(PrevIP, IP.Address);
135       if (!SameInlinee) {
136         State.switchToFrame(PrevIP);
137         State.CurrentLeafFrame->recordRangeCount(PrevIP, End, Repeat);
138         End = IP.Address;
139       }
140     }
141     assert(IP.Address == Target && "The last one must be the target address.");
142     // Record the remaining range, [0x01, 0x02] in the example
143     State.switchToFrame(IP.Address);
144     State.CurrentLeafFrame->recordRangeCount(IP.Address, End, Repeat);
145   }
146 }
147 
148 void VirtualUnwinder::unwindReturn(UnwindState &State) {
149   // Add extra frame as we unwind through the return
150   const LBREntry &LBR = State.getCurrentLBR();
151   uint64_t CallAddr = Binary->getCallAddrFromFrameAddr(LBR.Target);
152   State.switchToFrame(CallAddr);
153   // Push an external frame for the case of returning to external
154   // address(callback), later if an aitificial call is matched and it will be
155   // popped up. This is to 1)avoid context being interrupted by callback,
156   // context before or after the callback should be the same. 2) the call stack
157   // of function called by callback should be truncated which is done during
158   // recording the context on trie. For example:
159   //  main (call)--> foo (call)--> callback (call)--> bar (return)--> callback
160   //  (return)--> foo (return)--> main
161   // Context for bar should not include main and foo.
162   // For the code of foo, the context of before and after callback should both
163   // be [foo, main].
164   if (LBR.IsArtificial)
165     State.pushFrame(ExternalAddr);
166   State.pushFrame(LBR.Source);
167   State.InstPtr.update(LBR.Source);
168 }
169 
170 void VirtualUnwinder::unwindBranch(UnwindState &State) {
171   // TODO: Tolerate tail call for now, as we may see tail call from libraries.
172   // This is only for intra function branches, excluding tail calls.
173   uint64_t Source = State.getCurrentLBRSource();
174   State.switchToFrame(Source);
175   State.InstPtr.update(Source);
176 }
177 
178 std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {
179   std::shared_ptr<StringBasedCtxKey> KeyStr =
180       std::make_shared<StringBasedCtxKey>();
181   KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);
182   if (KeyStr->Context.empty())
183     return nullptr;
184   return KeyStr;
185 }
186 
187 std::shared_ptr<AddrBasedCtxKey> AddressStack::getContextKey() {
188   std::shared_ptr<AddrBasedCtxKey> KeyStr = std::make_shared<AddrBasedCtxKey>();
189   KeyStr->Context = Stack;
190   CSProfileGenerator::compressRecursionContext<uint64_t>(KeyStr->Context);
191   CSProfileGenerator::trimContext<uint64_t>(KeyStr->Context);
192   return KeyStr;
193 }
194 
195 template <typename T>
196 void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
197                                               T &Stack) {
198   if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
199     return;
200 
201   std::shared_ptr<ContextKey> Key = Stack.getContextKey();
202   if (Key == nullptr)
203     return;
204   auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());
205   SampleCounter &SCounter = Ret.first->second;
206   for (auto &Item : Cur->RangeSamples) {
207     uint64_t StartOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
208     uint64_t EndOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
209     SCounter.recordRangeCount(StartOffset, EndOffset, std::get<2>(Item));
210   }
211 
212   for (auto &Item : Cur->BranchSamples) {
213     uint64_t SourceOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
214     uint64_t TargetOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
215     SCounter.recordBranchCount(SourceOffset, TargetOffset, std::get<2>(Item));
216   }
217 }
218 
219 template <typename T>
220 void VirtualUnwinder::collectSamplesFromFrameTrie(
221     UnwindState::ProfiledFrame *Cur, T &Stack) {
222   if (!Cur->isDummyRoot()) {
223     // Truncate the context for external frame since this isn't a real call
224     // context the compiler will see.
225     if (Cur->isExternalFrame() || !Stack.pushFrame(Cur)) {
226       // Process truncated context
227       // Start a new traversal ignoring its bottom context
228       T EmptyStack(Binary);
229       collectSamplesFromFrame(Cur, EmptyStack);
230       for (const auto &Item : Cur->Children) {
231         collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);
232       }
233 
234       // Keep note of untracked call site and deduplicate them
235       // for warning later.
236       if (!Cur->isLeafFrame())
237         UntrackedCallsites.insert(Cur->Address);
238 
239       return;
240     }
241   }
242 
243   collectSamplesFromFrame(Cur, Stack);
244   // Process children frame
245   for (const auto &Item : Cur->Children) {
246     collectSamplesFromFrameTrie(Item.second.get(), Stack);
247   }
248   // Recover the call stack
249   Stack.popFrame();
250 }
251 
252 void VirtualUnwinder::collectSamplesFromFrameTrie(
253     UnwindState::ProfiledFrame *Cur) {
254   if (Binary->usePseudoProbes()) {
255     AddressStack Stack(Binary);
256     collectSamplesFromFrameTrie<AddressStack>(Cur, Stack);
257   } else {
258     FrameStack Stack(Binary);
259     collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);
260   }
261 }
262 
263 void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
264                                         UnwindState &State, uint64_t Repeat) {
265   if (Branch.IsArtificial || Branch.Target == ExternalAddr)
266     return;
267 
268   if (Binary->usePseudoProbes()) {
269     // Same as recordRangeCount, We don't need to top frame probe since we will
270     // extract it from branch's source address
271     State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,
272                                               Repeat);
273   } else {
274     State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,
275                                               Repeat);
276   }
277 }
278 
279 bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
280   // Capture initial state as starting point for unwinding.
281   UnwindState State(Sample, Binary);
282 
283   // Sanity check - making sure leaf of LBR aligns with leaf of stack sample
284   // Stack sample sometimes can be unreliable, so filter out bogus ones.
285   if (!State.validateInitialState())
286     return false;
287 
288   // Now process the LBR samples in parrallel with stack sample
289   // Note that we do not reverse the LBR entry order so we can
290   // unwind the sample stack as we walk through LBR entries.
291   while (State.hasNextLBR()) {
292     State.checkStateConsistency();
293 
294     // Do not attempt linear unwind for the leaf range as it's incomplete.
295     if (!State.IsLastLBR()) {
296       // Unwind implicit calls/returns from inlining, along the linear path,
297       // break into smaller sub section each with its own calling context.
298       unwindLinear(State, Repeat);
299     }
300 
301     // Save the LBR branch before it gets unwound.
302     const LBREntry &Branch = State.getCurrentLBR();
303 
304     if (isCallState(State)) {
305       // Unwind calls - we know we encountered call if LBR overlaps with
306       // transition between leaf the 2nd frame. Note that for calls that
307       // were not in the original stack sample, we should have added the
308       // extra frame when processing the return paired with this call.
309       unwindCall(State);
310     } else if (isReturnState(State)) {
311       // Unwind returns - check whether the IP is indeed at a return
312       // instruction
313       unwindReturn(State);
314     } else if (isValidState(State)) {
315       // Unwind branches
316       // For regular intra function branches, we only need to record branch
317       // with context. For an artificial branch cross function boundaries, we
318       // got an issue with returning to external code. Take the two LBR enties
319       // for example: [foo:8(RETURN), ext:1] [ext:3(CALL), bar:1] After perf
320       // reader, we only get[foo:8(RETURN), bar:1], unwinder will be confused
321       // like foo return to bar. Here we detect and treat this case as BRANCH
322       // instead of RETURN which only update the source address.
323       unwindBranch(State);
324     } else {
325       // Skip unwinding the rest of LBR trace. Reset the stack and update the
326       // state so that the rest of the trace can still be processed as if they
327       // do not have stack samples.
328       State.clearCallStack();
329       State.InstPtr.update(State.getCurrentLBRSource());
330       State.pushFrame(State.InstPtr.Address);
331     }
332 
333     State.advanceLBR();
334     // Record `branch` with calling context after unwinding.
335     recordBranchCount(Branch, State, Repeat);
336   }
337   // As samples are aggregated on trie, record them into counter map
338   collectSamplesFromFrameTrie(State.getDummyRootPtr());
339 
340   return true;
341 }
342 
343 std::unique_ptr<PerfReaderBase>
344 PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput,
345                        Optional<uint32_t> PIDFilter) {
346   std::unique_ptr<PerfReaderBase> PerfReader;
347 
348   if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {
349     PerfReader.reset(
350         new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));
351     return PerfReader;
352   }
353 
354   // For perf data input, we need to convert them into perf script first.
355   if (PerfInput.Format == PerfFormat::PerfData)
356     PerfInput =
357         PerfScriptReader::convertPerfDataToTrace(Binary, PerfInput, PIDFilter);
358 
359   assert((PerfInput.Format == PerfFormat::PerfScript) &&
360          "Should be a perfscript!");
361 
362   PerfInput.Content =
363       PerfScriptReader::checkPerfScriptType(PerfInput.InputFile);
364   if (PerfInput.Content == PerfContent::LBRStack) {
365     PerfReader.reset(
366         new HybridPerfReader(Binary, PerfInput.InputFile, PIDFilter));
367   } else if (PerfInput.Content == PerfContent::LBR) {
368     PerfReader.reset(new LBRPerfReader(Binary, PerfInput.InputFile, PIDFilter));
369   } else {
370     exitWithError("Unsupported perfscript!");
371   }
372 
373   return PerfReader;
374 }
375 
376 PerfInputFile PerfScriptReader::convertPerfDataToTrace(
377     ProfiledBinary *Binary, PerfInputFile &File, Optional<uint32_t> PIDFilter) {
378   StringRef PerfData = File.InputFile;
379   // Run perf script to retrieve PIDs matching binary we're interested in.
380   auto PerfExecutable = sys::Process::FindInEnvPath("PATH", "perf");
381   if (!PerfExecutable) {
382     exitWithError("Perf not found.");
383   }
384   std::string PerfPath = *PerfExecutable;
385   std::string PerfTraceFile = PerfData.str() + ".script.tmp";
386   StringRef ScriptMMapArgs[] = {PerfPath, "script",   "--show-mmap-events",
387                                 "-F",     "comm,pid", "-i",
388                                 PerfData};
389   Optional<StringRef> Redirects[] = {llvm::None,                // Stdin
390                                      StringRef(PerfTraceFile),  // Stdout
391                                      StringRef(PerfTraceFile)}; // Stderr
392   sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, llvm::None, Redirects);
393 
394   // Collect the PIDs
395   TraceStream TraceIt(PerfTraceFile);
396   std::string PIDs;
397   std::unordered_set<uint32_t> PIDSet;
398   while (!TraceIt.isAtEoF()) {
399     MMapEvent MMap;
400     if (isMMap2Event(TraceIt.getCurrentLine()) &&
401         extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap)) {
402       auto It = PIDSet.emplace(MMap.PID);
403       if (It.second && (!PIDFilter || MMap.PID == *PIDFilter)) {
404         if (!PIDs.empty()) {
405           PIDs.append(",");
406         }
407         PIDs.append(utostr(MMap.PID));
408       }
409     }
410     TraceIt.advance();
411   }
412 
413   if (PIDs.empty()) {
414     exitWithError("No relevant mmap event is found in perf data.");
415   }
416 
417   // Run perf script again to retrieve events for PIDs collected above
418   StringRef ScriptSampleArgs[] = {PerfPath, "script",     "--show-mmap-events",
419                                   "-F",     "ip,brstack", "--pid",
420                                   PIDs,     "-i",         PerfData};
421   sys::ExecuteAndWait(PerfPath, ScriptSampleArgs, llvm::None, Redirects);
422 
423   return {PerfTraceFile, PerfFormat::PerfScript, PerfContent::UnknownContent};
424 }
425 
426 void PerfScriptReader::updateBinaryAddress(const MMapEvent &Event) {
427   // Drop the event which doesn't belong to user-provided binary
428   StringRef BinaryName = llvm::sys::path::filename(Event.BinaryPath);
429   if (Binary->getName() != BinaryName)
430     return;
431 
432   // Drop the event if process does not match pid filter
433   if (PIDFilter && Event.PID != *PIDFilter)
434     return;
435 
436   // Drop the event if its image is loaded at the same address
437   if (Event.Address == Binary->getBaseAddress()) {
438     Binary->setIsLoadedByMMap(true);
439     return;
440   }
441 
442   if (Event.Offset == Binary->getTextSegmentOffset()) {
443     // A binary image could be unloaded and then reloaded at different
444     // place, so update binary load address.
445     // Only update for the first executable segment and assume all other
446     // segments are loaded at consecutive memory addresses, which is the case on
447     // X64.
448     Binary->setBaseAddress(Event.Address);
449     Binary->setIsLoadedByMMap(true);
450   } else {
451     // Verify segments are loaded consecutively.
452     const auto &Offsets = Binary->getTextSegmentOffsets();
453     auto It = std::lower_bound(Offsets.begin(), Offsets.end(), Event.Offset);
454     if (It != Offsets.end() && *It == Event.Offset) {
455       // The event is for loading a separate executable segment.
456       auto I = std::distance(Offsets.begin(), It);
457       const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();
458       if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=
459           Event.Address - Binary->getBaseAddress())
460         exitWithError("Executable segments not loaded consecutively");
461     } else {
462       if (It == Offsets.begin())
463         exitWithError("File offset not found");
464       else {
465         // Find the segment the event falls in. A large segment could be loaded
466         // via multiple mmap calls with consecutive memory addresses.
467         --It;
468         assert(*It < Event.Offset);
469         if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())
470           exitWithError("Segment not loaded by consecutive mmaps");
471       }
472     }
473   }
474 }
475 
476 static std::string getContextKeyStr(ContextKey *K,
477                                     const ProfiledBinary *Binary) {
478   if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {
479     return SampleContext::getContextString(CtxKey->Context);
480   } else if (const auto *CtxKey = dyn_cast<AddrBasedCtxKey>(K)) {
481     std::ostringstream OContextStr;
482     for (uint32_t I = 0; I < CtxKey->Context.size(); I++) {
483       if (OContextStr.str().size())
484         OContextStr << " @ ";
485       OContextStr << "0x"
486                   << to_hexString(
487                          Binary->virtualAddrToOffset(CtxKey->Context[I]),
488                          false);
489     }
490     return OContextStr.str();
491   } else {
492     llvm_unreachable("unexpected key type");
493   }
494 }
495 
496 void HybridPerfReader::unwindSamples() {
497   if (Binary->useFSDiscriminator())
498     exitWithError("FS discriminator is not supported in CS profile.");
499   VirtualUnwinder Unwinder(&SampleCounters, Binary);
500   for (const auto &Item : AggregatedSamples) {
501     const PerfSample *Sample = Item.first.getPtr();
502     Unwinder.unwind(Sample, Item.second);
503   }
504 
505   // Warn about untracked frames due to missing probes.
506   if (ShowDetailedWarning) {
507     for (auto Address : Unwinder.getUntrackedCallsites())
508       WithColor::warning() << "Profile context truncated due to missing probe "
509                            << "for call instruction at "
510                            << format("0x%" PRIx64, Address) << "\n";
511   }
512 
513   emitWarningSummary(Unwinder.getUntrackedCallsites().size(),
514                      SampleCounters.size(),
515                      "of profiled contexts are truncated due to missing probe "
516                      "for call instruction.");
517 
518   emitWarningSummary(
519       Unwinder.NumMismatchedExtCallBranch, Unwinder.NumTotalBranches,
520       "of branches'source is a call instruction but doesn't match call frame "
521       "stack, likely due to unwinding error of external frame.");
522 
523   emitWarningSummary(
524       Unwinder.NumMismatchedProEpiBranch, Unwinder.NumTotalBranches,
525       "of branches'source is a call instruction but doesn't match call frame "
526       "stack, likely due to frame in prolog/epilog.");
527 
528   emitWarningSummary(Unwinder.NumMissingExternalFrame,
529                      Unwinder.NumExtCallBranch,
530                      "of artificial call branches but doesn't have an external "
531                      "frame to match.");
532 }
533 
534 bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,
535                                        SmallVectorImpl<LBREntry> &LBRStack) {
536   // The raw format of LBR stack is like:
537   // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
538   //                           ... 0x4005c8/0x4005dc/P/-/-/0
539   // It's in FIFO order and seperated by whitespace.
540   SmallVector<StringRef, 32> Records;
541   TraceIt.getCurrentLine().split(Records, " ", -1, false);
542   auto WarnInvalidLBR = [](TraceStream &TraceIt) {
543     WithColor::warning() << "Invalid address in LBR record at line "
544                          << TraceIt.getLineNumber() << ": "
545                          << TraceIt.getCurrentLine() << "\n";
546   };
547 
548   // Skip the leading instruction pointer.
549   size_t Index = 0;
550   uint64_t LeadingAddr;
551   if (!Records.empty() && !Records[0].contains('/')) {
552     if (Records[0].getAsInteger(16, LeadingAddr)) {
553       WarnInvalidLBR(TraceIt);
554       TraceIt.advance();
555       return false;
556     }
557     Index = 1;
558   }
559   // Now extract LBR samples - note that we do not reverse the
560   // LBR entry order so we can unwind the sample stack as we walk
561   // through LBR entries.
562   uint64_t PrevTrDst = 0;
563 
564   while (Index < Records.size()) {
565     auto &Token = Records[Index++];
566     if (Token.size() == 0)
567       continue;
568 
569     SmallVector<StringRef, 8> Addresses;
570     Token.split(Addresses, "/");
571     uint64_t Src;
572     uint64_t Dst;
573 
574     // Stop at broken LBR records.
575     if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
576         Addresses[1].substr(2).getAsInteger(16, Dst)) {
577       WarnInvalidLBR(TraceIt);
578       break;
579     }
580 
581     bool SrcIsInternal = Binary->addressIsCode(Src);
582     bool DstIsInternal = Binary->addressIsCode(Dst);
583     bool IsExternal = !SrcIsInternal && !DstIsInternal;
584     bool IsIncoming = !SrcIsInternal && DstIsInternal;
585     bool IsOutgoing = SrcIsInternal && !DstIsInternal;
586     bool IsArtificial = false;
587 
588     // Ignore branches outside the current binary.
589     if (IsExternal) {
590       if (!PrevTrDst && !LBRStack.empty()) {
591         WithColor::warning()
592             << "Invalid transfer to external code in LBR record at line "
593             << TraceIt.getLineNumber() << ": " << TraceIt.getCurrentLine()
594             << "\n";
595       }
596       // Do not ignore the entire samples, the remaining LBR can still be
597       // unwound using a context-less stack.
598       continue;
599     }
600 
601     if (IsOutgoing) {
602       if (!PrevTrDst) {
603         // This is a leading outgoing LBR, we should keep processing the LBRs.
604         if (LBRStack.empty()) {
605           NumLeadingOutgoingLBR++;
606           // Record this LBR since current source and next LBR' target is still
607           // a valid range.
608           LBRStack.emplace_back(LBREntry(Src, ExternalAddr, false));
609           continue;
610         }
611         // This is middle unpaired outgoing jump which is likely due to
612         // interrupt or incomplete LBR trace. Ignore current and subsequent
613         // entries since they are likely in different contexts.
614         break;
615       }
616 
617       // For transition to external code, group the Source with the next
618       // availabe transition target.
619       Dst = PrevTrDst;
620       PrevTrDst = 0;
621       IsArtificial = true;
622     } else {
623       if (PrevTrDst) {
624         // If we have seen an incoming transition from external code to internal
625         // code, but not a following outgoing transition, the incoming
626         // transition is likely due to interrupt which is usually unpaired.
627         // Ignore current and subsequent entries since they are likely in
628         // different contexts.
629         break;
630       }
631 
632       if (IsIncoming) {
633         // For transition from external code (such as dynamic libraries) to
634         // the current binary, keep track of the branch target which will be
635         // grouped with the Source of the last transition from the current
636         // binary.
637         PrevTrDst = Dst;
638         continue;
639       }
640     }
641 
642     // TODO: filter out buggy duplicate branches on Skylake
643 
644     LBRStack.emplace_back(LBREntry(Src, Dst, IsArtificial));
645   }
646   TraceIt.advance();
647   return !LBRStack.empty();
648 }
649 
650 bool PerfScriptReader::extractCallstack(TraceStream &TraceIt,
651                                         SmallVectorImpl<uint64_t> &CallStack) {
652   // The raw format of call stack is like:
653   //            4005dc      # leaf frame
654   //	          400634
655   //	          400684      # root frame
656   // It's in bottom-up order with each frame in one line.
657 
658   // Extract stack frames from sample
659   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
660     StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
661     uint64_t FrameAddr = 0;
662     if (FrameStr.getAsInteger(16, FrameAddr)) {
663       // We might parse a non-perf sample line like empty line and comments,
664       // skip it
665       TraceIt.advance();
666       return false;
667     }
668     TraceIt.advance();
669     // Currently intermixed frame from different binaries is not supported.
670     if (!Binary->addressIsCode(FrameAddr)) {
671       if (CallStack.empty())
672         NumLeafExternalFrame++;
673       // Push a special value(ExternalAddr) for the external frames so that
674       // unwinder can still work on this with artificial Call/Return branch.
675       // After unwinding, the context will be truncated for external frame.
676       // Also deduplicate the consecutive external addresses.
677       if (CallStack.empty() || CallStack.back() != ExternalAddr)
678         CallStack.emplace_back(ExternalAddr);
679       continue;
680     }
681 
682     // We need to translate return address to call address for non-leaf frames.
683     if (!CallStack.empty()) {
684       auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
685       if (!CallAddr) {
686         // Stop at an invalid return address caused by bad unwinding. This could
687         // happen to frame-pointer-based unwinding and the callee functions that
688         // do not have the frame pointer chain set up.
689         InvalidReturnAddresses.insert(FrameAddr);
690         break;
691       }
692       FrameAddr = CallAddr;
693     }
694 
695     CallStack.emplace_back(FrameAddr);
696   }
697 
698   // Strip out the bottom external addr.
699   if (CallStack.size() > 1 && CallStack.back() == ExternalAddr)
700     CallStack.pop_back();
701 
702   // Skip other unrelated line, find the next valid LBR line
703   // Note that even for empty call stack, we should skip the address at the
704   // bottom, otherwise the following pass may generate a truncated callstack
705   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
706     TraceIt.advance();
707   }
708   // Filter out broken stack sample. We may not have complete frame info
709   // if sample end up in prolog/epilog, the result is dangling context not
710   // connected to entry point. This should be relatively rare thus not much
711   // impact on overall profile quality. However we do want to filter them
712   // out to reduce the number of different calling contexts. One instance
713   // of such case - when sample landed in prolog/epilog, somehow stack
714   // walking will be broken in an unexpected way that higher frames will be
715   // missing.
716   return !CallStack.empty() &&
717          !Binary->addressInPrologEpilog(CallStack.front());
718 }
719 
720 void PerfScriptReader::warnIfMissingMMap() {
721   if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
722     WithColor::warning() << "No relevant mmap event is matched for "
723                          << Binary->getName()
724                          << ", will use preferred address ("
725                          << format("0x%" PRIx64,
726                                    Binary->getPreferredBaseAddress())
727                          << ") as the base loading address!\n";
728     // Avoid redundant warning, only warn at the first unmatched sample.
729     Binary->setMissingMMapWarned(true);
730   }
731 }
732 
733 void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
734   // The raw hybird sample started with call stack in FILO order and followed
735   // intermediately by LBR sample
736   // e.g.
737   // 	          4005dc    # call stack leaf
738   //	          400634
739   //	          400684    # call stack root
740   // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
741   //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
742   //
743   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
744 #ifndef NDEBUG
745   Sample->Linenum = TraceIt.getLineNumber();
746 #endif
747   // Parsing call stack and populate into PerfSample.CallStack
748   if (!extractCallstack(TraceIt, Sample->CallStack)) {
749     // Skip the next LBR line matched current call stack
750     if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x"))
751       TraceIt.advance();
752     return;
753   }
754 
755   warnIfMissingMMap();
756 
757   if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x")) {
758     // Parsing LBR stack and populate into PerfSample.LBRStack
759     if (extractLBRStack(TraceIt, Sample->LBRStack)) {
760       if (IgnoreStackSamples) {
761         Sample->CallStack.clear();
762       } else {
763         // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
764         // ranges
765         Sample->CallStack.front() = Sample->LBRStack[0].Target;
766       }
767       // Record samples by aggregation
768       AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
769     }
770   } else {
771     // LBR sample is encoded in single line after stack sample
772     exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
773   }
774 }
775 
776 void PerfScriptReader::writeUnsymbolizedProfile(StringRef Filename) {
777   std::error_code EC;
778   raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
779   if (EC)
780     exitWithError(EC, Filename);
781   writeUnsymbolizedProfile(OS);
782 }
783 
784 // Use ordered map to make the output deterministic
785 using OrderedCounterForPrint = std::map<std::string, SampleCounter *>;
786 
787 void PerfScriptReader::writeUnsymbolizedProfile(raw_fd_ostream &OS) {
788   OrderedCounterForPrint OrderedCounters;
789   for (auto &CI : SampleCounters) {
790     OrderedCounters[getContextKeyStr(CI.first.getPtr(), Binary)] = &CI.second;
791   }
792 
793   auto SCounterPrinter = [&](RangeSample &Counter, StringRef Separator,
794                              uint32_t Indent) {
795     OS.indent(Indent);
796     OS << Counter.size() << "\n";
797     for (auto &I : Counter) {
798       uint64_t Start = I.first.first;
799       uint64_t End = I.first.second;
800 
801       if (!UseOffset || (UseOffset && UseLoadableSegmentAsBase)) {
802         Start = Binary->offsetToVirtualAddr(Start);
803         End = Binary->offsetToVirtualAddr(End);
804       }
805 
806       if (UseOffset && UseLoadableSegmentAsBase) {
807         Start -= Binary->getFirstLoadableAddress();
808         End -= Binary->getFirstLoadableAddress();
809       }
810 
811       OS.indent(Indent);
812       OS << Twine::utohexstr(Start) << Separator << Twine::utohexstr(End) << ":"
813          << I.second << "\n";
814     }
815   };
816 
817   for (auto &CI : OrderedCounters) {
818     uint32_t Indent = 0;
819     if (ProfileIsCSFlat) {
820       // Context string key
821       OS << "[" << CI.first << "]\n";
822       Indent = 2;
823     }
824 
825     SampleCounter &Counter = *CI.second;
826     SCounterPrinter(Counter.RangeCounter, "-", Indent);
827     SCounterPrinter(Counter.BranchCounter, "->", Indent);
828   }
829 }
830 
831 // Format of input:
832 // number of entries in RangeCounter
833 // from_1-to_1:count_1
834 // from_2-to_2:count_2
835 // ......
836 // from_n-to_n:count_n
837 // number of entries in BranchCounter
838 // src_1->dst_1:count_1
839 // src_2->dst_2:count_2
840 // ......
841 // src_n->dst_n:count_n
842 void UnsymbolizedProfileReader::readSampleCounters(TraceStream &TraceIt,
843                                                    SampleCounter &SCounters) {
844   auto exitWithErrorForTraceLine = [](TraceStream &TraceIt) {
845     std::string Msg = TraceIt.isAtEoF()
846                           ? "Invalid raw profile!"
847                           : "Invalid raw profile at line " +
848                                 Twine(TraceIt.getLineNumber()).str() + ": " +
849                                 TraceIt.getCurrentLine().str();
850     exitWithError(Msg);
851   };
852   auto ReadNumber = [&](uint64_t &Num) {
853     if (TraceIt.isAtEoF())
854       exitWithErrorForTraceLine(TraceIt);
855     if (TraceIt.getCurrentLine().ltrim().getAsInteger(10, Num))
856       exitWithErrorForTraceLine(TraceIt);
857     TraceIt.advance();
858   };
859 
860   auto ReadCounter = [&](RangeSample &Counter, StringRef Separator) {
861     uint64_t Num = 0;
862     ReadNumber(Num);
863     while (Num--) {
864       if (TraceIt.isAtEoF())
865         exitWithErrorForTraceLine(TraceIt);
866       StringRef Line = TraceIt.getCurrentLine().ltrim();
867 
868       uint64_t Count = 0;
869       auto LineSplit = Line.split(":");
870       if (LineSplit.second.empty() || LineSplit.second.getAsInteger(10, Count))
871         exitWithErrorForTraceLine(TraceIt);
872 
873       uint64_t Source = 0;
874       uint64_t Target = 0;
875       auto Range = LineSplit.first.split(Separator);
876       if (Range.second.empty() || Range.first.getAsInteger(16, Source) ||
877           Range.second.getAsInteger(16, Target))
878         exitWithErrorForTraceLine(TraceIt);
879 
880       if (!UseOffset || (UseOffset && UseLoadableSegmentAsBase)) {
881         uint64_t BaseAddr = 0;
882         if (UseOffset && UseLoadableSegmentAsBase)
883           BaseAddr = Binary->getFirstLoadableAddress();
884 
885         Source = Binary->virtualAddrToOffset(Source + BaseAddr);
886         Target = Binary->virtualAddrToOffset(Target + BaseAddr);
887       }
888 
889       Counter[{Source, Target}] += Count;
890       TraceIt.advance();
891     }
892   };
893 
894   ReadCounter(SCounters.RangeCounter, "-");
895   ReadCounter(SCounters.BranchCounter, "->");
896 }
897 
898 void UnsymbolizedProfileReader::readUnsymbolizedProfile(StringRef FileName) {
899   TraceStream TraceIt(FileName);
900   while (!TraceIt.isAtEoF()) {
901     std::shared_ptr<StringBasedCtxKey> Key =
902         std::make_shared<StringBasedCtxKey>();
903     StringRef Line = TraceIt.getCurrentLine();
904     // Read context stack for CS profile.
905     if (Line.startswith("[")) {
906       ProfileIsCSFlat = true;
907       auto I = ContextStrSet.insert(Line.str());
908       SampleContext::createCtxVectorFromStr(*I.first, Key->Context);
909       TraceIt.advance();
910     }
911     auto Ret =
912         SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
913     readSampleCounters(TraceIt, Ret.first->second);
914   }
915 }
916 
917 void UnsymbolizedProfileReader::parsePerfTraces() {
918   readUnsymbolizedProfile(PerfTraceFile);
919 }
920 
921 void PerfScriptReader::computeCounterFromLBR(const PerfSample *Sample,
922                                              uint64_t Repeat) {
923   SampleCounter &Counter = SampleCounters.begin()->second;
924   uint64_t EndOffeset = 0;
925   for (const LBREntry &LBR : Sample->LBRStack) {
926     assert(LBR.Source != ExternalAddr &&
927            "Branch' source should not be an external address, it should be "
928            "converted to aritificial branch.");
929     uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
930     uint64_t TargetOffset = LBR.Target == static_cast<uint64_t>(ExternalAddr)
931                                 ? static_cast<uint64_t>(ExternalAddr)
932                                 : Binary->virtualAddrToOffset(LBR.Target);
933 
934     if (!LBR.IsArtificial && TargetOffset != ExternalAddr) {
935       Counter.recordBranchCount(SourceOffset, TargetOffset, Repeat);
936     }
937 
938     // If this not the first LBR, update the range count between TO of current
939     // LBR and FROM of next LBR.
940     uint64_t StartOffset = TargetOffset;
941     if (EndOffeset != 0) {
942       if (StartOffset <= EndOffeset)
943         Counter.recordRangeCount(StartOffset, EndOffeset, Repeat);
944     }
945     EndOffeset = SourceOffset;
946   }
947 }
948 
949 void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
950   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
951   // Parsing LBR stack and populate into PerfSample.LBRStack
952   if (extractLBRStack(TraceIt, Sample->LBRStack)) {
953     warnIfMissingMMap();
954     // Record LBR only samples by aggregation
955     AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
956   }
957 }
958 
959 void PerfScriptReader::generateUnsymbolizedProfile() {
960   // There is no context for LBR only sample, so initialize one entry with
961   // fake "empty" context key.
962   assert(SampleCounters.empty() &&
963          "Sample counter map should be empty before raw profile generation");
964   std::shared_ptr<StringBasedCtxKey> Key =
965       std::make_shared<StringBasedCtxKey>();
966   SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
967   for (const auto &Item : AggregatedSamples) {
968     const PerfSample *Sample = Item.first.getPtr();
969     computeCounterFromLBR(Sample, Item.second);
970   }
971 }
972 
973 uint64_t PerfScriptReader::parseAggregatedCount(TraceStream &TraceIt) {
974   // The aggregated count is optional, so do not skip the line and return 1 if
975   // it's unmatched
976   uint64_t Count = 1;
977   if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
978     TraceIt.advance();
979   return Count;
980 }
981 
982 void PerfScriptReader::parseSample(TraceStream &TraceIt) {
983   NumTotalSample++;
984   uint64_t Count = parseAggregatedCount(TraceIt);
985   assert(Count >= 1 && "Aggregated count should be >= 1!");
986   parseSample(TraceIt, Count);
987 }
988 
989 bool PerfScriptReader::extractMMap2EventForBinary(ProfiledBinary *Binary,
990                                                   StringRef Line,
991                                                   MMapEvent &MMap) {
992   // Parse a line like:
993   //  PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
994   //  08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
995   constexpr static const char *const Pattern =
996       "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
997       "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
998       "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
999   // Field 0 - whole line
1000   // Field 1 - PID
1001   // Field 2 - base address
1002   // Field 3 - mmapped size
1003   // Field 4 - page offset
1004   // Field 5 - binary path
1005   enum EventIndex {
1006     WHOLE_LINE = 0,
1007     PID = 1,
1008     MMAPPED_ADDRESS = 2,
1009     MMAPPED_SIZE = 3,
1010     PAGE_OFFSET = 4,
1011     BINARY_PATH = 5
1012   };
1013 
1014   Regex RegMmap2(Pattern);
1015   SmallVector<StringRef, 6> Fields;
1016   bool R = RegMmap2.match(Line, &Fields);
1017   if (!R) {
1018     std::string ErrorMsg = "Cannot parse mmap event: " + Line.str() + " \n";
1019     exitWithError(ErrorMsg);
1020   }
1021   Fields[PID].getAsInteger(10, MMap.PID);
1022   Fields[MMAPPED_ADDRESS].getAsInteger(0, MMap.Address);
1023   Fields[MMAPPED_SIZE].getAsInteger(0, MMap.Size);
1024   Fields[PAGE_OFFSET].getAsInteger(0, MMap.Offset);
1025   MMap.BinaryPath = Fields[BINARY_PATH];
1026   if (ShowMmapEvents) {
1027     outs() << "Mmap: Binary " << MMap.BinaryPath << " loaded at "
1028            << format("0x%" PRIx64 ":", MMap.Address) << " \n";
1029   }
1030 
1031   StringRef BinaryName = llvm::sys::path::filename(MMap.BinaryPath);
1032   return Binary->getName() == BinaryName;
1033 }
1034 
1035 void PerfScriptReader::parseMMap2Event(TraceStream &TraceIt) {
1036   MMapEvent MMap;
1037   if (extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap))
1038     updateBinaryAddress(MMap);
1039   TraceIt.advance();
1040 }
1041 
1042 void PerfScriptReader::parseEventOrSample(TraceStream &TraceIt) {
1043   if (isMMap2Event(TraceIt.getCurrentLine()))
1044     parseMMap2Event(TraceIt);
1045   else
1046     parseSample(TraceIt);
1047 }
1048 
1049 void PerfScriptReader::parseAndAggregateTrace() {
1050   // Trace line iterator
1051   TraceStream TraceIt(PerfTraceFile);
1052   while (!TraceIt.isAtEoF())
1053     parseEventOrSample(TraceIt);
1054 }
1055 
1056 // A LBR sample is like:
1057 // 40062f 0x5c6313f/0x5c63170/P/-/-/0  0x5c630e7/0x5c63130/P/-/-/0 ...
1058 // A heuristic for fast detection by checking whether a
1059 // leading "  0x" and the '/' exist.
1060 bool PerfScriptReader::isLBRSample(StringRef Line) {
1061   // Skip the leading instruction pointer
1062   SmallVector<StringRef, 32> Records;
1063   Line.trim().split(Records, " ", 2, false);
1064   if (Records.size() < 2)
1065     return false;
1066   if (Records[1].startswith("0x") && Records[1].contains('/'))
1067     return true;
1068   return false;
1069 }
1070 
1071 bool PerfScriptReader::isMMap2Event(StringRef Line) {
1072   // Short cut to avoid string find is possible.
1073   if (Line.empty() || Line.size() < 50)
1074     return false;
1075 
1076   if (std::isdigit(Line[0]))
1077     return false;
1078 
1079   // PERF_RECORD_MMAP2 does not appear at the beginning of the line
1080   // for ` perf script  --show-mmap-events  -i ...`
1081   return Line.contains("PERF_RECORD_MMAP2");
1082 }
1083 
1084 // The raw hybird sample is like
1085 // e.g.
1086 // 	          4005dc    # call stack leaf
1087 //	          400634
1088 //	          400684    # call stack root
1089 // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
1090 //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
1091 // Determine the perfscript contains hybrid samples(call stack + LBRs) by
1092 // checking whether there is a non-empty call stack immediately followed by
1093 // a LBR sample
1094 PerfContent PerfScriptReader::checkPerfScriptType(StringRef FileName) {
1095   TraceStream TraceIt(FileName);
1096   uint64_t FrameAddr = 0;
1097   while (!TraceIt.isAtEoF()) {
1098     // Skip the aggregated count
1099     if (!TraceIt.getCurrentLine().getAsInteger(10, FrameAddr))
1100       TraceIt.advance();
1101 
1102     // Detect sample with call stack
1103     int32_t Count = 0;
1104     while (!TraceIt.isAtEoF() &&
1105            !TraceIt.getCurrentLine().ltrim().getAsInteger(16, FrameAddr)) {
1106       Count++;
1107       TraceIt.advance();
1108     }
1109     if (!TraceIt.isAtEoF()) {
1110       if (isLBRSample(TraceIt.getCurrentLine())) {
1111         if (Count > 0)
1112           return PerfContent::LBRStack;
1113         else
1114           return PerfContent::LBR;
1115       }
1116       TraceIt.advance();
1117     }
1118   }
1119 
1120   exitWithError("Invalid perf script input!");
1121   return PerfContent::UnknownContent;
1122 }
1123 
1124 void HybridPerfReader::generateUnsymbolizedProfile() {
1125   ProfileIsCSFlat = !IgnoreStackSamples;
1126   if (ProfileIsCSFlat)
1127     unwindSamples();
1128   else
1129     PerfScriptReader::generateUnsymbolizedProfile();
1130 }
1131 
1132 void PerfScriptReader::warnTruncatedStack() {
1133   if (ShowDetailedWarning) {
1134     for (auto Address : InvalidReturnAddresses) {
1135       WithColor::warning()
1136           << "Truncated stack sample due to invalid return address at "
1137           << format("0x%" PRIx64, Address)
1138           << ", likely caused by frame pointer omission\n";
1139     }
1140   }
1141   emitWarningSummary(
1142       InvalidReturnAddresses.size(), AggregatedSamples.size(),
1143       "of truncated stack samples due to invalid return address, "
1144       "likely caused by frame pointer omission.");
1145 }
1146 
1147 void PerfScriptReader::warnInvalidRange() {
1148   std::unordered_map<std::pair<uint64_t, uint64_t>, uint64_t,
1149                      pair_hash<uint64_t, uint64_t>>
1150       Ranges;
1151 
1152   for (const auto &Item : AggregatedSamples) {
1153     const PerfSample *Sample = Item.first.getPtr();
1154     uint64_t Count = Item.second;
1155     uint64_t EndOffeset = 0;
1156     for (const LBREntry &LBR : Sample->LBRStack) {
1157       uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
1158       uint64_t StartOffset = Binary->virtualAddrToOffset(LBR.Target);
1159       if (EndOffeset != 0)
1160         Ranges[{StartOffset, EndOffeset}] += Count;
1161       EndOffeset = SourceOffset;
1162     }
1163   }
1164 
1165   if (Ranges.empty()) {
1166     WithColor::warning() << "No samples in perf script!\n";
1167     return;
1168   }
1169 
1170   auto WarnInvalidRange =
1171       [&](uint64_t StartOffset, uint64_t EndOffset, StringRef Msg) {
1172         if (!ShowDetailedWarning)
1173           return;
1174         WithColor::warning()
1175             << "["
1176             << format("%8" PRIx64, Binary->offsetToVirtualAddr(StartOffset))
1177             << ","
1178             << format("%8" PRIx64, Binary->offsetToVirtualAddr(EndOffset))
1179             << "]: " << Msg << "\n";
1180       };
1181 
1182   const char *EndNotBoundaryMsg = "Range is not on instruction boundary, "
1183                                   "likely due to profile and binary mismatch.";
1184   const char *DanglingRangeMsg = "Range does not belong to any functions, "
1185                                  "likely from PLT, .init or .fini section.";
1186   const char *RangeCrossFuncMsg =
1187       "Fall through range should not cross function boundaries, likely due to "
1188       "profile and binary mismatch.";
1189   const char *BogusRangeMsg = "Range start is after range end.";
1190 
1191   uint64_t TotalRangeNum = 0;
1192   uint64_t InstNotBoundary = 0;
1193   uint64_t UnmatchedRange = 0;
1194   uint64_t RangeCrossFunc = 0;
1195   uint64_t BogusRange = 0;
1196 
1197   for (auto &I : Ranges) {
1198     uint64_t StartOffset = I.first.first;
1199     uint64_t EndOffset = I.first.second;
1200     TotalRangeNum += I.second;
1201 
1202     if (!Binary->offsetIsCode(StartOffset) ||
1203         !Binary->offsetIsTransfer(EndOffset)) {
1204       InstNotBoundary += I.second;
1205       WarnInvalidRange(StartOffset, EndOffset, EndNotBoundaryMsg);
1206     }
1207 
1208     auto *FRange = Binary->findFuncRangeForOffset(StartOffset);
1209     if (!FRange) {
1210       UnmatchedRange += I.second;
1211       WarnInvalidRange(StartOffset, EndOffset, DanglingRangeMsg);
1212       continue;
1213     }
1214 
1215     if (EndOffset >= FRange->EndOffset) {
1216       RangeCrossFunc += I.second;
1217       WarnInvalidRange(StartOffset, EndOffset, RangeCrossFuncMsg);
1218     }
1219 
1220     if (StartOffset > EndOffset) {
1221       BogusRange += I.second;
1222       WarnInvalidRange(StartOffset, EndOffset, BogusRangeMsg);
1223     }
1224   }
1225 
1226   emitWarningSummary(
1227       InstNotBoundary, TotalRangeNum,
1228       "of samples are from ranges that are not on instruction boundary.");
1229   emitWarningSummary(
1230       UnmatchedRange, TotalRangeNum,
1231       "of samples are from ranges that do not belong to any functions.");
1232   emitWarningSummary(
1233       RangeCrossFunc, TotalRangeNum,
1234       "of samples are from ranges that do cross function boundaries.");
1235   emitWarningSummary(
1236       BogusRange, TotalRangeNum,
1237       "of samples are from ranges that have range start after range end.");
1238 }
1239 
1240 void PerfScriptReader::parsePerfTraces() {
1241   // Parse perf traces and do aggregation.
1242   parseAndAggregateTrace();
1243 
1244   emitWarningSummary(NumLeafExternalFrame, NumTotalSample,
1245                      "of samples have leaf external frame in call stack.");
1246   emitWarningSummary(NumLeadingOutgoingLBR, NumTotalSample,
1247                      "of samples have leading external LBR.");
1248 
1249   // Generate unsymbolized profile.
1250   warnTruncatedStack();
1251   warnInvalidRange();
1252   generateUnsymbolizedProfile();
1253   AggregatedSamples.clear();
1254 
1255   if (SkipSymbolization)
1256     writeUnsymbolizedProfile(OutputFilename);
1257 }
1258 
1259 } // end namespace sampleprof
1260 } // end namespace llvm
1261