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 
12 #define DEBUG_TYPE "perf-reader"
13 
14 static cl::opt<bool> ShowMmapEvents("show-mmap-events", cl::ReallyHidden,
15                                     cl::init(false), cl::ZeroOrMore,
16                                     cl::desc("Print binary load events."));
17 
18 cl::opt<bool> SkipSymbolization("skip-symbolization", cl::ReallyHidden,
19                                 cl::init(false), cl::ZeroOrMore,
20                                 cl::desc("Dump the unsymbolized profile to the "
21                                          "output file. It will show unwinder "
22                                          "output for CS profile generation."));
23 
24 extern cl::opt<bool> ShowDisassemblyOnly;
25 extern cl::opt<bool> ShowSourceLocations;
26 extern cl::opt<std::string> OutputFilename;
27 
28 namespace llvm {
29 namespace sampleprof {
30 
31 void VirtualUnwinder::unwindCall(UnwindState &State) {
32   // The 2nd frame after leaf could be missing if stack sample is
33   // taken when IP is within prolog/epilog, as frame chain isn't
34   // setup yet. Fill in the missing frame in that case.
35   // TODO: Currently we just assume all the addr that can't match the
36   // 2nd frame is in prolog/epilog. In the future, we will switch to
37   // pro/epi tracker(Dwarf CFI) for the precise check.
38   uint64_t Source = State.getCurrentLBRSource();
39   auto *ParentFrame = State.getParentFrame();
40   if (ParentFrame == State.getDummyRootPtr() ||
41       ParentFrame->Address != Source) {
42     State.switchToFrame(Source);
43   } else {
44     State.popFrame();
45   }
46   State.InstPtr.update(Source);
47 }
48 
49 void VirtualUnwinder::unwindLinear(UnwindState &State, uint64_t Repeat) {
50   InstructionPointer &IP = State.InstPtr;
51   uint64_t Target = State.getCurrentLBRTarget();
52   uint64_t End = IP.Address;
53   if (Binary->usePseudoProbes()) {
54     // We don't need to top frame probe since it should be extracted
55     // from the range.
56     // The outcome of the virtual unwinding with pseudo probes is a
57     // map from a context key to the address range being unwound.
58     // This means basically linear unwinding is not needed for pseudo
59     // probes. The range will be simply recorded here and will be
60     // converted to a list of pseudo probes to report in ProfileGenerator.
61     State.getParentFrame()->recordRangeCount(Target, End, Repeat);
62   } else {
63     // Unwind linear execution part.
64     // Split and record the range by different inline context. For example:
65     // [0x01] ... main:1          # Target
66     // [0x02] ... main:2
67     // [0x03] ... main:3 @ foo:1
68     // [0x04] ... main:3 @ foo:2
69     // [0x05] ... main:3 @ foo:3
70     // [0x06] ... main:4
71     // [0x07] ... main:5          # End
72     // It will be recorded:
73     // [main:*]         : [0x06, 0x07], [0x01, 0x02]
74     // [main:3 @ foo:*] : [0x03, 0x05]
75     while (IP.Address > Target) {
76       uint64_t PrevIP = IP.Address;
77       IP.backward();
78       // Break into segments for implicit call/return due to inlining
79       bool SameInlinee = Binary->inlineContextEqual(PrevIP, IP.Address);
80       if (!SameInlinee) {
81         State.switchToFrame(PrevIP);
82         State.CurrentLeafFrame->recordRangeCount(PrevIP, End, Repeat);
83         End = IP.Address;
84       }
85     }
86     assert(IP.Address == Target && "The last one must be the target address.");
87     // Record the remaining range, [0x01, 0x02] in the example
88     State.switchToFrame(IP.Address);
89     State.CurrentLeafFrame->recordRangeCount(IP.Address, End, Repeat);
90   }
91 }
92 
93 void VirtualUnwinder::unwindReturn(UnwindState &State) {
94   // Add extra frame as we unwind through the return
95   const LBREntry &LBR = State.getCurrentLBR();
96   uint64_t CallAddr = Binary->getCallAddrFromFrameAddr(LBR.Target);
97   State.switchToFrame(CallAddr);
98   State.pushFrame(LBR.Source);
99   State.InstPtr.update(LBR.Source);
100 }
101 
102 void VirtualUnwinder::unwindBranchWithinFrame(UnwindState &State) {
103   // TODO: Tolerate tail call for now, as we may see tail call from libraries.
104   // This is only for intra function branches, excluding tail calls.
105   uint64_t Source = State.getCurrentLBRSource();
106   State.switchToFrame(Source);
107   State.InstPtr.update(Source);
108 }
109 
110 std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {
111   std::shared_ptr<StringBasedCtxKey> KeyStr =
112       std::make_shared<StringBasedCtxKey>();
113   KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);
114   if (KeyStr->Context.empty())
115     return nullptr;
116   KeyStr->genHashCode();
117   return KeyStr;
118 }
119 
120 std::shared_ptr<ProbeBasedCtxKey> ProbeStack::getContextKey() {
121   std::shared_ptr<ProbeBasedCtxKey> ProbeBasedKey =
122       std::make_shared<ProbeBasedCtxKey>();
123   for (auto CallProbe : Stack) {
124     ProbeBasedKey->Probes.emplace_back(CallProbe);
125   }
126   CSProfileGenerator::compressRecursionContext<const MCDecodedPseudoProbe *>(
127       ProbeBasedKey->Probes);
128   CSProfileGenerator::trimContext<const MCDecodedPseudoProbe *>(
129       ProbeBasedKey->Probes);
130 
131   ProbeBasedKey->genHashCode();
132   return ProbeBasedKey;
133 }
134 
135 template <typename T>
136 void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
137                                               T &Stack) {
138   if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
139     return;
140 
141   std::shared_ptr<ContextKey> Key = Stack.getContextKey();
142   if (Key == nullptr)
143     return;
144   auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());
145   SampleCounter &SCounter = Ret.first->second;
146   for (auto &Item : Cur->RangeSamples) {
147     uint64_t StartOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
148     uint64_t EndOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
149     SCounter.recordRangeCount(StartOffset, EndOffset, std::get<2>(Item));
150   }
151 
152   for (auto &Item : Cur->BranchSamples) {
153     uint64_t SourceOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
154     uint64_t TargetOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
155     SCounter.recordBranchCount(SourceOffset, TargetOffset, std::get<2>(Item));
156   }
157 }
158 
159 template <typename T>
160 void VirtualUnwinder::collectSamplesFromFrameTrie(
161     UnwindState::ProfiledFrame *Cur, T &Stack) {
162   if (!Cur->isDummyRoot()) {
163     if (!Stack.pushFrame(Cur)) {
164       // Process truncated context
165       // Start a new traversal ignoring its bottom context
166       T EmptyStack(Binary);
167       collectSamplesFromFrame(Cur, EmptyStack);
168       for (const auto &Item : Cur->Children) {
169         collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);
170       }
171 
172       // Keep note of untracked call site and deduplicate them
173       // for warning later.
174       if (!Cur->isLeafFrame())
175         UntrackedCallsites.insert(Cur->Address);
176 
177       return;
178     }
179   }
180 
181   collectSamplesFromFrame(Cur, Stack);
182   // Process children frame
183   for (const auto &Item : Cur->Children) {
184     collectSamplesFromFrameTrie(Item.second.get(), Stack);
185   }
186   // Recover the call stack
187   Stack.popFrame();
188 }
189 
190 void VirtualUnwinder::collectSamplesFromFrameTrie(
191     UnwindState::ProfiledFrame *Cur) {
192   if (Binary->usePseudoProbes()) {
193     ProbeStack Stack(Binary);
194     collectSamplesFromFrameTrie<ProbeStack>(Cur, Stack);
195   } else {
196     FrameStack Stack(Binary);
197     collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);
198   }
199 }
200 
201 void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
202                                         UnwindState &State, uint64_t Repeat) {
203   if (Branch.IsArtificial)
204     return;
205 
206   if (Binary->usePseudoProbes()) {
207     // Same as recordRangeCount, We don't need to top frame probe since we will
208     // extract it from branch's source address
209     State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,
210                                               Repeat);
211   } else {
212     State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,
213                                               Repeat);
214   }
215 }
216 
217 bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
218   // Capture initial state as starting point for unwinding.
219   UnwindState State(Sample, Binary);
220 
221   // Sanity check - making sure leaf of LBR aligns with leaf of stack sample
222   // Stack sample sometimes can be unreliable, so filter out bogus ones.
223   if (!State.validateInitialState())
224     return false;
225 
226   // Also do not attempt linear unwind for the leaf range as it's incomplete.
227   bool IsLeaf = true;
228 
229   // Now process the LBR samples in parrallel with stack sample
230   // Note that we do not reverse the LBR entry order so we can
231   // unwind the sample stack as we walk through LBR entries.
232   while (State.hasNextLBR()) {
233     State.checkStateConsistency();
234 
235     // Unwind implicit calls/returns from inlining, along the linear path,
236     // break into smaller sub section each with its own calling context.
237     if (!IsLeaf) {
238       unwindLinear(State, Repeat);
239     }
240     IsLeaf = false;
241 
242     // Save the LBR branch before it gets unwound.
243     const LBREntry &Branch = State.getCurrentLBR();
244 
245     if (isCallState(State)) {
246       // Unwind calls - we know we encountered call if LBR overlaps with
247       // transition between leaf the 2nd frame. Note that for calls that
248       // were not in the original stack sample, we should have added the
249       // extra frame when processing the return paired with this call.
250       unwindCall(State);
251     } else if (isReturnState(State)) {
252       // Unwind returns - check whether the IP is indeed at a return instruction
253       unwindReturn(State);
254     } else {
255       // Unwind branches - for regular intra function branches, we only
256       // need to record branch with context.
257       unwindBranchWithinFrame(State);
258     }
259     State.advanceLBR();
260     // Record `branch` with calling context after unwinding.
261     recordBranchCount(Branch, State, Repeat);
262   }
263   // As samples are aggregated on trie, record them into counter map
264   collectSamplesFromFrameTrie(State.getDummyRootPtr());
265 
266   return true;
267 }
268 
269 std::unique_ptr<PerfReaderBase>
270 PerfReaderBase::create(ProfiledBinary *Binary,
271                        cl::list<std::string> &PerfTraceFilenames) {
272   PerfScriptType PerfType = extractPerfType(PerfTraceFilenames);
273   std::unique_ptr<PerfReaderBase> PerfReader;
274   if (PerfType == PERF_LBR_STACK) {
275     PerfReader.reset(new HybridPerfReader(Binary));
276   } else if (PerfType == PERF_LBR) {
277     PerfReader.reset(new LBRPerfReader(Binary));
278   } else {
279     exitWithError("Unsupported perfscript!");
280   }
281 
282   return PerfReader;
283 }
284 
285 void PerfReaderBase::updateBinaryAddress(const MMapEvent &Event) {
286   // Drop the event which doesn't belong to user-provided binary
287   StringRef BinaryName = llvm::sys::path::filename(Event.BinaryPath);
288   if (Binary->getName() != BinaryName)
289     return;
290 
291   // Drop the event if its image is loaded at the same address
292   if (Event.Address == Binary->getBaseAddress()) {
293     Binary->setIsLoadedByMMap(true);
294     return;
295   }
296 
297   if (Event.Offset == Binary->getTextSegmentOffset()) {
298     // A binary image could be unloaded and then reloaded at different
299     // place, so update binary load address.
300     // Only update for the first executable segment and assume all other
301     // segments are loaded at consecutive memory addresses, which is the case on
302     // X64.
303     Binary->setBaseAddress(Event.Address);
304     Binary->setIsLoadedByMMap(true);
305   } else {
306     // Verify segments are loaded consecutively.
307     const auto &Offsets = Binary->getTextSegmentOffsets();
308     auto It = std::lower_bound(Offsets.begin(), Offsets.end(), Event.Offset);
309     if (It != Offsets.end() && *It == Event.Offset) {
310       // The event is for loading a separate executable segment.
311       auto I = std::distance(Offsets.begin(), It);
312       const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();
313       if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=
314           Event.Address - Binary->getBaseAddress())
315         exitWithError("Executable segments not loaded consecutively");
316     } else {
317       if (It == Offsets.begin())
318         exitWithError("File offset not found");
319       else {
320         // Find the segment the event falls in. A large segment could be loaded
321         // via multiple mmap calls with consecutive memory addresses.
322         --It;
323         assert(*It < Event.Offset);
324         if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())
325           exitWithError("Segment not loaded by consecutive mmaps");
326       }
327     }
328   }
329 }
330 
331 // Use ordered map to make the output deterministic
332 using OrderedCounterForPrint = std::map<std::string, RangeSample>;
333 
334 static void printSampleCounter(OrderedCounterForPrint &OrderedCounter,
335                                raw_fd_ostream &OS) {
336   for (auto Range : OrderedCounter) {
337     OS << Range.first << "\n";
338     for (auto I : Range.second) {
339       OS << "  (" << format("%" PRIx64, I.first.first) << ", "
340          << format("%" PRIx64, I.first.second) << "): " << I.second << "\n";
341     }
342   }
343 }
344 
345 static std::string getContextKeyStr(ContextKey *K,
346                                     const ProfiledBinary *Binary) {
347   if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {
348     return SampleContext::getContextString(CtxKey->Context);
349   } else if (const auto *CtxKey = dyn_cast<ProbeBasedCtxKey>(K)) {
350     SampleContextFrameVector ContextStack;
351     for (const auto *Probe : CtxKey->Probes) {
352       Binary->getInlineContextForProbe(Probe, ContextStack, true);
353     }
354     // Probe context key at this point does not have leaf probe, so do not
355     // include the leaf inline location.
356     return SampleContext::getContextString(ContextStack, true);
357   } else {
358     llvm_unreachable("unexpected key type");
359   }
360 }
361 
362 static void printRangeCounter(ContextSampleCounterMap &Counter,
363                               const ProfiledBinary *Binary,
364                               raw_fd_ostream &OS) {
365   OrderedCounterForPrint OrderedCounter;
366   for (auto &CI : Counter) {
367     OrderedCounter[getContextKeyStr(CI.first.getPtr(), Binary)] =
368         CI.second.RangeCounter;
369   }
370   printSampleCounter(OrderedCounter, OS);
371 }
372 
373 static void printBranchCounter(ContextSampleCounterMap &Counter,
374                                const ProfiledBinary *Binary,
375                                raw_fd_ostream &OS) {
376   OrderedCounterForPrint OrderedCounter;
377   for (auto &CI : Counter) {
378     OrderedCounter[getContextKeyStr(CI.first.getPtr(), Binary)] =
379         CI.second.BranchCounter;
380   }
381   printSampleCounter(OrderedCounter, OS);
382 }
383 
384 void HybridPerfReader::writeRawProfile(raw_fd_ostream &OS) {
385   OS << "Binary(" << Binary->getName().str() << ")'s Range Counter:\n";
386   printRangeCounter(SampleCounters, Binary, OS);
387   OS << "\nBinary(" << Binary->getName().str() << ")'s Branch Counter:\n";
388   printBranchCounter(SampleCounters, Binary, OS);
389 }
390 
391 void HybridPerfReader::unwindSamples() {
392   std::set<uint64_t> AllUntrackedCallsites;
393   for (const auto &Item : AggregatedSamples) {
394     const PerfSample *Sample = Item.first.getPtr();
395     VirtualUnwinder Unwinder(&SampleCounters, Binary);
396     Unwinder.unwind(Sample, Item.second);
397     auto &CurrUntrackedCallsites = Unwinder.getUntrackedCallsites();
398     AllUntrackedCallsites.insert(CurrUntrackedCallsites.begin(),
399                                  CurrUntrackedCallsites.end());
400   }
401 
402   // Warn about untracked frames due to missing probes.
403   for (auto Address : AllUntrackedCallsites)
404     WithColor::warning() << "Profile context truncated due to missing probe "
405                          << "for call instruction at "
406                          << format("%" PRIx64, Address) << "\n";
407 
408   if (SkipSymbolization)
409     PerfReaderBase::writeRawProfile(OutputFilename);
410 }
411 
412 bool PerfReaderBase::extractLBRStack(TraceStream &TraceIt,
413                                      SmallVectorImpl<LBREntry> &LBRStack) {
414   // The raw format of LBR stack is like:
415   // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
416   //                           ... 0x4005c8/0x4005dc/P/-/-/0
417   // It's in FIFO order and seperated by whitespace.
418   SmallVector<StringRef, 32> Records;
419   TraceIt.getCurrentLine().split(Records, " ", -1, false);
420   auto WarnInvalidLBR = [](TraceStream &TraceIt) {
421     WithColor::warning() << "Invalid address in LBR record at line "
422                          << TraceIt.getLineNumber() << ": "
423                          << TraceIt.getCurrentLine() << "\n";
424   };
425 
426   // Skip the leading instruction pointer.
427   size_t Index = 0;
428   uint64_t LeadingAddr;
429   if (!Records.empty() && Records[0].find('/') == StringRef::npos) {
430     if (Records[0].getAsInteger(16, LeadingAddr)) {
431       WarnInvalidLBR(TraceIt);
432       TraceIt.advance();
433       return false;
434     }
435     Index = 1;
436   }
437   // Now extract LBR samples - note that we do not reverse the
438   // LBR entry order so we can unwind the sample stack as we walk
439   // through LBR entries.
440   uint64_t PrevTrDst = 0;
441 
442   while (Index < Records.size()) {
443     auto &Token = Records[Index++];
444     if (Token.size() == 0)
445       continue;
446 
447     SmallVector<StringRef, 8> Addresses;
448     Token.split(Addresses, "/");
449     uint64_t Src;
450     uint64_t Dst;
451 
452     // Stop at broken LBR records.
453     if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
454         Addresses[1].substr(2).getAsInteger(16, Dst)) {
455       WarnInvalidLBR(TraceIt);
456       break;
457     }
458 
459     bool SrcIsInternal = Binary->addressIsCode(Src);
460     bool DstIsInternal = Binary->addressIsCode(Dst);
461     bool IsExternal = !SrcIsInternal && !DstIsInternal;
462     bool IsIncoming = !SrcIsInternal && DstIsInternal;
463     bool IsOutgoing = SrcIsInternal && !DstIsInternal;
464     bool IsArtificial = false;
465 
466     // Ignore branches outside the current binary.
467     if (IsExternal)
468       continue;
469 
470     if (IsOutgoing) {
471       if (!PrevTrDst) {
472         // This is unpaired outgoing jump which is likely due to interrupt or
473         // incomplete LBR trace. Ignore current and subsequent entries since
474         // they are likely in different contexts.
475         break;
476       }
477 
478       if (Binary->addressIsReturn(Src)) {
479         // In a callback case, a return from internal code, say A, to external
480         // runtime can happen. The external runtime can then call back to
481         // another internal routine, say B. Making an artificial branch that
482         // looks like a return from A to B can confuse the unwinder to treat
483         // the instruction before B as the call instruction.
484         break;
485       }
486 
487       // For transition to external code, group the Source with the next
488       // availabe transition target.
489       Dst = PrevTrDst;
490       PrevTrDst = 0;
491       IsArtificial = true;
492     } else {
493       if (PrevTrDst) {
494         // If we have seen an incoming transition from external code to internal
495         // code, but not a following outgoing transition, the incoming
496         // transition is likely due to interrupt which is usually unpaired.
497         // Ignore current and subsequent entries since they are likely in
498         // different contexts.
499         break;
500       }
501 
502       if (IsIncoming) {
503         // For transition from external code (such as dynamic libraries) to
504         // the current binary, keep track of the branch target which will be
505         // grouped with the Source of the last transition from the current
506         // binary.
507         PrevTrDst = Dst;
508         continue;
509       }
510     }
511 
512     // TODO: filter out buggy duplicate branches on Skylake
513 
514     LBRStack.emplace_back(LBREntry(Src, Dst, IsArtificial));
515   }
516   TraceIt.advance();
517   return !LBRStack.empty();
518 }
519 
520 bool PerfReaderBase::extractCallstack(TraceStream &TraceIt,
521                                       SmallVectorImpl<uint64_t> &CallStack) {
522   // The raw format of call stack is like:
523   //            4005dc      # leaf frame
524   //	          400634
525   //	          400684      # root frame
526   // It's in bottom-up order with each frame in one line.
527 
528   // Extract stack frames from sample
529   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
530     StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
531     uint64_t FrameAddr = 0;
532     if (FrameStr.getAsInteger(16, FrameAddr)) {
533       // We might parse a non-perf sample line like empty line and comments,
534       // skip it
535       TraceIt.advance();
536       return false;
537     }
538     TraceIt.advance();
539     // Currently intermixed frame from different binaries is not supported.
540     // Ignore bottom frames not from binary of interest.
541     if (!Binary->addressIsCode(FrameAddr))
542       break;
543 
544     // We need to translate return address to call address for non-leaf frames.
545     if (!CallStack.empty()) {
546       auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
547       if (!CallAddr) {
548         // Stop at an invalid return address caused by bad unwinding. This could
549         // happen to frame-pointer-based unwinding and the callee functions that
550         // do not have the frame pointer chain set up.
551         InvalidReturnAddresses.insert(FrameAddr);
552         break;
553       }
554       FrameAddr = CallAddr;
555     }
556 
557     CallStack.emplace_back(FrameAddr);
558   }
559 
560   // Skip other unrelated line, find the next valid LBR line
561   // Note that even for empty call stack, we should skip the address at the
562   // bottom, otherwise the following pass may generate a truncated callstack
563   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
564     TraceIt.advance();
565   }
566   // Filter out broken stack sample. We may not have complete frame info
567   // if sample end up in prolog/epilog, the result is dangling context not
568   // connected to entry point. This should be relatively rare thus not much
569   // impact on overall profile quality. However we do want to filter them
570   // out to reduce the number of different calling contexts. One instance
571   // of such case - when sample landed in prolog/epilog, somehow stack
572   // walking will be broken in an unexpected way that higher frames will be
573   // missing.
574   return !CallStack.empty() &&
575          !Binary->addressInPrologEpilog(CallStack.front());
576 }
577 
578 void PerfReaderBase::warnIfMissingMMap() {
579   if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
580     WithColor::warning() << "No relevant mmap event is matched, will use "
581                             "preferred address as the base loading address!\n";
582     // Avoid redundant warning, only warn at the first unmatched sample.
583     Binary->setMissingMMapWarned(true);
584   }
585 }
586 
587 void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
588   // The raw hybird sample started with call stack in FILO order and followed
589   // intermediately by LBR sample
590   // e.g.
591   // 	          4005dc    # call stack leaf
592   //	          400634
593   //	          400684    # call stack root
594   // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
595   //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
596   //
597   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
598 
599   // Parsing call stack and populate into PerfSample.CallStack
600   if (!extractCallstack(TraceIt, Sample->CallStack)) {
601     // Skip the next LBR line matched current call stack
602     if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x"))
603       TraceIt.advance();
604     return;
605   }
606 
607   warnIfMissingMMap();
608 
609   if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x")) {
610     // Parsing LBR stack and populate into PerfSample.LBRStack
611     if (extractLBRStack(TraceIt, Sample->LBRStack)) {
612       // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
613       // ranges
614       Sample->CallStack.front() = Sample->LBRStack[0].Target;
615       // Record samples by aggregation
616       AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
617     }
618   } else {
619     // LBR sample is encoded in single line after stack sample
620     exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
621   }
622 }
623 
624 void PerfReaderBase::writeRawProfile(StringRef Filename) {
625   std::error_code EC;
626   raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
627   if (EC)
628     exitWithError(EC, Filename);
629   writeRawProfile(OS);
630 }
631 
632 void LBRPerfReader::writeRawProfile(raw_fd_ostream &OS) {
633   /*
634      Format:
635      number of entries in RangeCounter
636      from_1-to_1:count_1
637      from_2-to_2:count_2
638      ......
639      from_n-to_n:count_n
640      number of entries in BranchCounter
641      src_1->dst_1:count_1
642      src_2->dst_2:count_2
643      ......
644      src_n->dst_n:count_n
645   */
646 
647   SampleCounter &Counter = SampleCounters.begin()->second;
648   OS << Counter.RangeCounter.size() << "\n";
649   for (auto I : Counter.RangeCounter) {
650     OS << Twine::utohexstr(I.first.first) << "-"
651        << Twine::utohexstr(I.first.second) << ":" << I.second << "\n";
652   }
653 
654   OS << Counter.BranchCounter.size() << "\n";
655   for (auto I : Counter.BranchCounter) {
656     OS << Twine::utohexstr(I.first.first) << "->"
657        << Twine::utohexstr(I.first.second) << ":" << I.second << "\n";
658   }
659 }
660 
661 void LBRPerfReader::computeCounterFromLBR(const PerfSample *Sample,
662                                           uint64_t Repeat) {
663   SampleCounter &Counter = SampleCounters.begin()->second;
664   uint64_t EndOffeset = 0;
665   for (const LBREntry &LBR : Sample->LBRStack) {
666     uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
667     uint64_t TargetOffset = Binary->virtualAddrToOffset(LBR.Target);
668 
669     if (!LBR.IsArtificial) {
670       Counter.recordBranchCount(SourceOffset, TargetOffset, Repeat);
671     }
672 
673     // If this not the first LBR, update the range count between TO of current
674     // LBR and FROM of next LBR.
675     uint64_t StartOffset = TargetOffset;
676     if (EndOffeset != 0)
677       Counter.recordRangeCount(StartOffset, EndOffeset, Repeat);
678     EndOffeset = SourceOffset;
679   }
680 }
681 
682 void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
683   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
684   // Parsing LBR stack and populate into PerfSample.LBRStack
685   if (extractLBRStack(TraceIt, Sample->LBRStack)) {
686     warnIfMissingMMap();
687     // Record LBR only samples by aggregation
688     AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
689   }
690 }
691 
692 void LBRPerfReader::generateRawProfile() {
693   assert(SampleCounters.size() == 1 && "Must have one entry of sample counter");
694   for (const auto &Item : AggregatedSamples) {
695     const PerfSample *Sample = Item.first.getPtr();
696     computeCounterFromLBR(Sample, Item.second);
697   }
698 
699   if (SkipSymbolization)
700     PerfReaderBase::writeRawProfile(OutputFilename);
701 }
702 
703 uint64_t PerfReaderBase::parseAggregatedCount(TraceStream &TraceIt) {
704   // The aggregated count is optional, so do not skip the line and return 1 if
705   // it's unmatched
706   uint64_t Count = 1;
707   if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
708     TraceIt.advance();
709   return Count;
710 }
711 
712 void PerfReaderBase::parseSample(TraceStream &TraceIt) {
713   uint64_t Count = parseAggregatedCount(TraceIt);
714   assert(Count >= 1 && "Aggregated count should be >= 1!");
715   parseSample(TraceIt, Count);
716 }
717 
718 void PerfReaderBase::parseMMap2Event(TraceStream &TraceIt) {
719   // Parse a line like:
720   //  PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
721   //  08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
722   constexpr static const char *const Pattern =
723       "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
724       "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
725       "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
726   // Field 0 - whole line
727   // Field 1 - PID
728   // Field 2 - base address
729   // Field 3 - mmapped size
730   // Field 4 - page offset
731   // Field 5 - binary path
732   enum EventIndex {
733     WHOLE_LINE = 0,
734     PID = 1,
735     MMAPPED_ADDRESS = 2,
736     MMAPPED_SIZE = 3,
737     PAGE_OFFSET = 4,
738     BINARY_PATH = 5
739   };
740 
741   Regex RegMmap2(Pattern);
742   SmallVector<StringRef, 6> Fields;
743   bool R = RegMmap2.match(TraceIt.getCurrentLine(), &Fields);
744   if (!R) {
745     std::string ErrorMsg = "Cannot parse mmap event: Line" +
746                            Twine(TraceIt.getLineNumber()).str() + ": " +
747                            TraceIt.getCurrentLine().str() + " \n";
748     exitWithError(ErrorMsg);
749   }
750   MMapEvent Event;
751   Fields[PID].getAsInteger(10, Event.PID);
752   Fields[MMAPPED_ADDRESS].getAsInteger(0, Event.Address);
753   Fields[MMAPPED_SIZE].getAsInteger(0, Event.Size);
754   Fields[PAGE_OFFSET].getAsInteger(0, Event.Offset);
755   Event.BinaryPath = Fields[BINARY_PATH];
756   updateBinaryAddress(Event);
757   if (ShowMmapEvents) {
758     outs() << "Mmap: Binary " << Event.BinaryPath << " loaded at "
759            << format("0x%" PRIx64 ":", Event.Address) << " \n";
760   }
761   TraceIt.advance();
762 }
763 
764 void PerfReaderBase::parseEventOrSample(TraceStream &TraceIt) {
765   if (TraceIt.getCurrentLine().startswith("PERF_RECORD_MMAP2"))
766     parseMMap2Event(TraceIt);
767   else
768     parseSample(TraceIt);
769 }
770 
771 void PerfReaderBase::parseAndAggregateTrace(StringRef Filename) {
772   // Trace line iterator
773   TraceStream TraceIt(Filename);
774   while (!TraceIt.isAtEoF())
775     parseEventOrSample(TraceIt);
776 }
777 
778 PerfScriptType
779 PerfReaderBase::extractPerfType(cl::list<std::string> &PerfTraceFilenames) {
780   PerfScriptType PerfType = PERF_UNKNOWN;
781   for (auto FileName : PerfTraceFilenames) {
782     PerfScriptType Type = checkPerfScriptType(FileName);
783     if (Type == PERF_INVALID)
784       exitWithError("Invalid perf script input!");
785     if (PerfType != PERF_UNKNOWN && PerfType != Type)
786       exitWithError("Inconsistent sample among different perf scripts");
787     PerfType = Type;
788   }
789   return PerfType;
790 }
791 
792 void HybridPerfReader::generateRawProfile() { unwindSamples(); }
793 
794 void PerfReaderBase::warnTruncatedStack() {
795   for (auto Address : InvalidReturnAddresses) {
796     WithColor::warning()
797         << "Truncated stack sample due to invalid return address at "
798         << format("0x%" PRIx64, Address)
799         << ", likely caused by frame pointer omission\n";
800   }
801 }
802 
803 void PerfReaderBase::parsePerfTraces(
804     cl::list<std::string> &PerfTraceFilenames) {
805   // Parse perf traces and do aggregation.
806   for (auto Filename : PerfTraceFilenames)
807     parseAndAggregateTrace(Filename);
808 
809   warnTruncatedStack();
810   generateRawProfile();
811 }
812 
813 } // end namespace sampleprof
814 } // end namespace llvm
815