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