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