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