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