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 (Target > End) {
103     // Skip unwinding the rest of LBR trace when a bogus range is seen.
104     State.setInvalid();
105     return;
106   }
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   State.pushFrame(LBR.Source);
154   State.InstPtr.update(LBR.Source);
155 }
156 
157 void VirtualUnwinder::unwindBranch(UnwindState &State) {
158   // TODO: Tolerate tail call for now, as we may see tail call from libraries.
159   // This is only for intra function branches, excluding tail calls.
160   uint64_t Source = State.getCurrentLBRSource();
161   State.switchToFrame(Source);
162   State.InstPtr.update(Source);
163 }
164 
165 std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {
166   std::shared_ptr<StringBasedCtxKey> KeyStr =
167       std::make_shared<StringBasedCtxKey>();
168   KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);
169   return KeyStr;
170 }
171 
172 std::shared_ptr<AddrBasedCtxKey> AddressStack::getContextKey() {
173   std::shared_ptr<AddrBasedCtxKey> KeyStr = std::make_shared<AddrBasedCtxKey>();
174   KeyStr->Context = Stack;
175   CSProfileGenerator::compressRecursionContext<uint64_t>(KeyStr->Context);
176   CSProfileGenerator::trimContext<uint64_t>(KeyStr->Context);
177   return KeyStr;
178 }
179 
180 template <typename T>
181 void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
182                                               T &Stack) {
183   if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
184     return;
185 
186   std::shared_ptr<ContextKey> Key = Stack.getContextKey();
187   if (Key == nullptr)
188     return;
189   auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());
190   SampleCounter &SCounter = Ret.first->second;
191   for (auto &Item : Cur->RangeSamples) {
192     uint64_t StartOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
193     uint64_t EndOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
194     SCounter.recordRangeCount(StartOffset, EndOffset, std::get<2>(Item));
195   }
196 
197   for (auto &Item : Cur->BranchSamples) {
198     uint64_t SourceOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
199     uint64_t TargetOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
200     SCounter.recordBranchCount(SourceOffset, TargetOffset, std::get<2>(Item));
201   }
202 }
203 
204 template <typename T>
205 void VirtualUnwinder::collectSamplesFromFrameTrie(
206     UnwindState::ProfiledFrame *Cur, T &Stack) {
207   if (!Cur->isDummyRoot()) {
208     // Truncate the context for external frame since this isn't a real call
209     // context the compiler will see.
210     if (Cur->isExternalFrame() || !Stack.pushFrame(Cur)) {
211       // Process truncated context
212       // Start a new traversal ignoring its bottom context
213       T EmptyStack(Binary);
214       collectSamplesFromFrame(Cur, EmptyStack);
215       for (const auto &Item : Cur->Children) {
216         collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);
217       }
218 
219       // Keep note of untracked call site and deduplicate them
220       // for warning later.
221       if (!Cur->isLeafFrame())
222         UntrackedCallsites.insert(Cur->Address);
223 
224       return;
225     }
226   }
227 
228   collectSamplesFromFrame(Cur, Stack);
229   // Process children frame
230   for (const auto &Item : Cur->Children) {
231     collectSamplesFromFrameTrie(Item.second.get(), Stack);
232   }
233   // Recover the call stack
234   Stack.popFrame();
235 }
236 
237 void VirtualUnwinder::collectSamplesFromFrameTrie(
238     UnwindState::ProfiledFrame *Cur) {
239   if (Binary->usePseudoProbes()) {
240     AddressStack Stack(Binary);
241     collectSamplesFromFrameTrie<AddressStack>(Cur, Stack);
242   } else {
243     FrameStack Stack(Binary);
244     collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);
245   }
246 }
247 
248 void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
249                                         UnwindState &State, uint64_t Repeat) {
250   if (Branch.Target == ExternalAddr)
251     return;
252 
253   // Record external-to-internal pattern on the trie root, it later can be
254   // used for generating head samples.
255   if (Branch.Source == ExternalAddr) {
256     State.getDummyRootPtr()->recordBranchCount(Branch.Source, Branch.Target,
257                                                Repeat);
258     return;
259   }
260 
261   if (Binary->usePseudoProbes()) {
262     // Same as recordRangeCount, We don't need to top frame probe since we will
263     // extract it from branch's source address
264     State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,
265                                               Repeat);
266   } else {
267     State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,
268                                               Repeat);
269   }
270 }
271 
272 bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
273   // Capture initial state as starting point for unwinding.
274   UnwindState State(Sample, Binary);
275 
276   // Sanity check - making sure leaf of LBR aligns with leaf of stack sample
277   // Stack sample sometimes can be unreliable, so filter out bogus ones.
278   if (!State.validateInitialState())
279     return false;
280 
281   NumTotalBranches += State.LBRStack.size();
282   // Now process the LBR samples in parrallel with stack sample
283   // Note that we do not reverse the LBR entry order so we can
284   // unwind the sample stack as we walk through LBR entries.
285   while (State.hasNextLBR()) {
286     State.checkStateConsistency();
287 
288     // Do not attempt linear unwind for the leaf range as it's incomplete.
289     if (!State.IsLastLBR()) {
290       // Unwind implicit calls/returns from inlining, along the linear path,
291       // break into smaller sub section each with its own calling context.
292       unwindLinear(State, Repeat);
293     }
294 
295     // Save the LBR branch before it gets unwound.
296     const LBREntry &Branch = State.getCurrentLBR();
297     if (isCallState(State)) {
298       // Unwind calls - we know we encountered call if LBR overlaps with
299       // transition between leaf the 2nd frame. Note that for calls that
300       // were not in the original stack sample, we should have added the
301       // extra frame when processing the return paired with this call.
302       unwindCall(State);
303     } else if (isReturnState(State)) {
304       // Unwind returns - check whether the IP is indeed at a return
305       // instruction
306       unwindReturn(State);
307     } else if (isValidState(State)) {
308       // Unwind branches
309       unwindBranch(State);
310     } else {
311       // Skip unwinding the rest of LBR trace. Reset the stack and update the
312       // state so that the rest of the trace can still be processed as if they
313       // do not have stack samples.
314       State.clearCallStack();
315       State.InstPtr.update(State.getCurrentLBRSource());
316       State.pushFrame(State.InstPtr.Address);
317     }
318 
319     State.advanceLBR();
320     // Record `branch` with calling context after unwinding.
321     recordBranchCount(Branch, State, Repeat);
322   }
323   // As samples are aggregated on trie, record them into counter map
324   collectSamplesFromFrameTrie(State.getDummyRootPtr());
325 
326   return true;
327 }
328 
329 std::unique_ptr<PerfReaderBase>
330 PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput,
331                        Optional<uint32_t> PIDFilter) {
332   std::unique_ptr<PerfReaderBase> PerfReader;
333 
334   if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {
335     PerfReader.reset(
336         new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));
337     return PerfReader;
338   }
339 
340   // For perf data input, we need to convert them into perf script first.
341   if (PerfInput.Format == PerfFormat::PerfData)
342     PerfInput =
343         PerfScriptReader::convertPerfDataToTrace(Binary, PerfInput, PIDFilter);
344 
345   assert((PerfInput.Format == PerfFormat::PerfScript) &&
346          "Should be a perfscript!");
347 
348   PerfInput.Content =
349       PerfScriptReader::checkPerfScriptType(PerfInput.InputFile);
350   if (PerfInput.Content == PerfContent::LBRStack) {
351     PerfReader.reset(
352         new HybridPerfReader(Binary, PerfInput.InputFile, PIDFilter));
353   } else if (PerfInput.Content == PerfContent::LBR) {
354     PerfReader.reset(new LBRPerfReader(Binary, PerfInput.InputFile, PIDFilter));
355   } else {
356     exitWithError("Unsupported perfscript!");
357   }
358 
359   return PerfReader;
360 }
361 
362 PerfInputFile PerfScriptReader::convertPerfDataToTrace(
363     ProfiledBinary *Binary, PerfInputFile &File, Optional<uint32_t> PIDFilter) {
364   StringRef PerfData = File.InputFile;
365   // Run perf script to retrieve PIDs matching binary we're interested in.
366   auto PerfExecutable = sys::Process::FindInEnvPath("PATH", "perf");
367   if (!PerfExecutable) {
368     exitWithError("Perf not found.");
369   }
370   std::string PerfPath = *PerfExecutable;
371   std::string PerfTraceFile = PerfData.str() + ".script.tmp";
372   StringRef ScriptMMapArgs[] = {PerfPath, "script",   "--show-mmap-events",
373                                 "-F",     "comm,pid", "-i",
374                                 PerfData};
375   Optional<StringRef> Redirects[] = {llvm::None,                // Stdin
376                                      StringRef(PerfTraceFile),  // Stdout
377                                      StringRef(PerfTraceFile)}; // Stderr
378   sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, llvm::None, Redirects);
379 
380   // Collect the PIDs
381   TraceStream TraceIt(PerfTraceFile);
382   std::string PIDs;
383   std::unordered_set<uint32_t> PIDSet;
384   while (!TraceIt.isAtEoF()) {
385     MMapEvent MMap;
386     if (isMMap2Event(TraceIt.getCurrentLine()) &&
387         extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap)) {
388       auto It = PIDSet.emplace(MMap.PID);
389       if (It.second && (!PIDFilter || MMap.PID == *PIDFilter)) {
390         if (!PIDs.empty()) {
391           PIDs.append(",");
392         }
393         PIDs.append(utostr(MMap.PID));
394       }
395     }
396     TraceIt.advance();
397   }
398 
399   if (PIDs.empty()) {
400     exitWithError("No relevant mmap event is found in perf data.");
401   }
402 
403   // Run perf script again to retrieve events for PIDs collected above
404   StringRef ScriptSampleArgs[] = {PerfPath, "script",     "--show-mmap-events",
405                                   "-F",     "ip,brstack", "--pid",
406                                   PIDs,     "-i",         PerfData};
407   sys::ExecuteAndWait(PerfPath, ScriptSampleArgs, llvm::None, Redirects);
408 
409   return {PerfTraceFile, PerfFormat::PerfScript, PerfContent::UnknownContent};
410 }
411 
412 void PerfScriptReader::updateBinaryAddress(const MMapEvent &Event) {
413   // Drop the event which doesn't belong to user-provided binary
414   StringRef BinaryName = llvm::sys::path::filename(Event.BinaryPath);
415   if (Binary->getName() != BinaryName)
416     return;
417 
418   // Drop the event if process does not match pid filter
419   if (PIDFilter && Event.PID != *PIDFilter)
420     return;
421 
422   // Drop the event if its image is loaded at the same address
423   if (Event.Address == Binary->getBaseAddress()) {
424     Binary->setIsLoadedByMMap(true);
425     return;
426   }
427 
428   if (Event.Offset == Binary->getTextSegmentOffset()) {
429     // A binary image could be unloaded and then reloaded at different
430     // place, so update binary load address.
431     // Only update for the first executable segment and assume all other
432     // segments are loaded at consecutive memory addresses, which is the case on
433     // X64.
434     Binary->setBaseAddress(Event.Address);
435     Binary->setIsLoadedByMMap(true);
436   } else {
437     // Verify segments are loaded consecutively.
438     const auto &Offsets = Binary->getTextSegmentOffsets();
439     auto It = std::lower_bound(Offsets.begin(), Offsets.end(), Event.Offset);
440     if (It != Offsets.end() && *It == Event.Offset) {
441       // The event is for loading a separate executable segment.
442       auto I = std::distance(Offsets.begin(), It);
443       const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();
444       if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=
445           Event.Address - Binary->getBaseAddress())
446         exitWithError("Executable segments not loaded consecutively");
447     } else {
448       if (It == Offsets.begin())
449         exitWithError("File offset not found");
450       else {
451         // Find the segment the event falls in. A large segment could be loaded
452         // via multiple mmap calls with consecutive memory addresses.
453         --It;
454         assert(*It < Event.Offset);
455         if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())
456           exitWithError("Segment not loaded by consecutive mmaps");
457       }
458     }
459   }
460 }
461 
462 static std::string getContextKeyStr(ContextKey *K,
463                                     const ProfiledBinary *Binary) {
464   if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {
465     return SampleContext::getContextString(CtxKey->Context);
466   } else if (const auto *CtxKey = dyn_cast<AddrBasedCtxKey>(K)) {
467     std::ostringstream OContextStr;
468     for (uint32_t I = 0; I < CtxKey->Context.size(); I++) {
469       if (OContextStr.str().size())
470         OContextStr << " @ ";
471       OContextStr << "0x"
472                   << to_hexString(
473                          Binary->virtualAddrToOffset(CtxKey->Context[I]),
474                          false);
475     }
476     return OContextStr.str();
477   } else {
478     llvm_unreachable("unexpected key type");
479   }
480 }
481 
482 void HybridPerfReader::unwindSamples() {
483   if (Binary->useFSDiscriminator())
484     exitWithError("FS discriminator is not supported in CS profile.");
485   VirtualUnwinder Unwinder(&SampleCounters, Binary);
486   for (const auto &Item : AggregatedSamples) {
487     const PerfSample *Sample = Item.first.getPtr();
488     Unwinder.unwind(Sample, Item.second);
489   }
490 
491   // Warn about untracked frames due to missing probes.
492   if (ShowDetailedWarning) {
493     for (auto Address : Unwinder.getUntrackedCallsites())
494       WithColor::warning() << "Profile context truncated due to missing probe "
495                            << "for call instruction at "
496                            << format("0x%" PRIx64, Address) << "\n";
497   }
498 
499   emitWarningSummary(Unwinder.getUntrackedCallsites().size(),
500                      SampleCounters.size(),
501                      "of profiled contexts are truncated due to missing probe "
502                      "for call instruction.");
503 
504   emitWarningSummary(
505       Unwinder.NumMismatchedExtCallBranch, Unwinder.NumTotalBranches,
506       "of branches'source is a call instruction but doesn't match call frame "
507       "stack, likely due to unwinding error of external frame.");
508 
509   emitWarningSummary(Unwinder.NumPairedExtAddr * 2, Unwinder.NumTotalBranches,
510                      "of branches containing paired external address.");
511 
512   emitWarningSummary(Unwinder.NumUnpairedExtAddr, Unwinder.NumTotalBranches,
513                      "of branches containing external address but doesn't have "
514                      "another external address to pair, likely due to "
515                      "interrupt jmp or broken perf script.");
516 
517   emitWarningSummary(
518       Unwinder.NumMismatchedProEpiBranch, Unwinder.NumTotalBranches,
519       "of branches'source is a call instruction but doesn't match call frame "
520       "stack, likely due to frame in prolog/epilog.");
521 
522   emitWarningSummary(Unwinder.NumMissingExternalFrame,
523                      Unwinder.NumExtCallBranch,
524                      "of artificial call branches but doesn't have an external "
525                      "frame to match.");
526 }
527 
528 bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,
529                                        SmallVectorImpl<LBREntry> &LBRStack) {
530   // The raw format of LBR stack is like:
531   // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
532   //                           ... 0x4005c8/0x4005dc/P/-/-/0
533   // It's in FIFO order and seperated by whitespace.
534   SmallVector<StringRef, 32> Records;
535   TraceIt.getCurrentLine().split(Records, " ", -1, false);
536   auto WarnInvalidLBR = [](TraceStream &TraceIt) {
537     WithColor::warning() << "Invalid address in LBR record at line "
538                          << TraceIt.getLineNumber() << ": "
539                          << TraceIt.getCurrentLine() << "\n";
540   };
541 
542   // Skip the leading instruction pointer.
543   size_t Index = 0;
544   uint64_t LeadingAddr;
545   if (!Records.empty() && !Records[0].contains('/')) {
546     if (Records[0].getAsInteger(16, LeadingAddr)) {
547       WarnInvalidLBR(TraceIt);
548       TraceIt.advance();
549       return false;
550     }
551     Index = 1;
552   }
553 
554   // Now extract LBR samples - note that we do not reverse the
555   // LBR entry order so we can unwind the sample stack as we walk
556   // through LBR entries.
557   while (Index < Records.size()) {
558     auto &Token = Records[Index++];
559     if (Token.size() == 0)
560       continue;
561 
562     SmallVector<StringRef, 8> Addresses;
563     Token.split(Addresses, "/");
564     uint64_t Src;
565     uint64_t Dst;
566 
567     // Stop at broken LBR records.
568     if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
569         Addresses[1].substr(2).getAsInteger(16, Dst)) {
570       WarnInvalidLBR(TraceIt);
571       break;
572     }
573 
574     bool SrcIsInternal = Binary->addressIsCode(Src);
575     bool DstIsInternal = Binary->addressIsCode(Dst);
576     if (!SrcIsInternal)
577       Src = ExternalAddr;
578     if (!DstIsInternal)
579       Dst = ExternalAddr;
580     // Filter external-to-external case to reduce LBR trace size.
581     if (!SrcIsInternal && !DstIsInternal)
582       continue;
583 
584     // TODO: filter out buggy duplicate branches on Skylake
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 (ProfileIsCSFlat) {
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       ProfileIsCSFlat = 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         StartOffset <= EndOffeset)
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   ProfileIsCSFlat = !IgnoreStackSamples;
1064   if (ProfileIsCSFlat)
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 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 (StartOffset > EndOffset) {
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 range end.");
1176 }
1177 
1178 void PerfScriptReader::parsePerfTraces() {
1179   // Parse perf traces and do aggregation.
1180   parseAndAggregateTrace();
1181 
1182   emitWarningSummary(NumLeafExternalFrame, NumTotalSample,
1183                      "of samples have leaf external frame in call stack.");
1184   emitWarningSummary(NumLeadingOutgoingLBR, NumTotalSample,
1185                      "of samples have leading external LBR.");
1186 
1187   // Generate unsymbolized profile.
1188   warnTruncatedStack();
1189   warnInvalidRange();
1190   generateUnsymbolizedProfile();
1191   AggregatedSamples.clear();
1192 
1193   if (SkipSymbolization)
1194     writeUnsymbolizedProfile(OutputFilename);
1195 }
1196 
1197 } // end namespace sampleprof
1198 } // end namespace llvm
1199