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 
421   // Skip the leading instruction pointer.
422   size_t Index = 0;
423   if (!Records.empty() && Records[0].find('/') == StringRef::npos) {
424     Index = 1;
425   }
426   // Now extract LBR samples - note that we do not reverse the
427   // LBR entry order so we can unwind the sample stack as we walk
428   // through LBR entries.
429   uint64_t PrevTrDst = 0;
430 
431   while (Index < Records.size()) {
432     auto &Token = Records[Index++];
433     if (Token.size() == 0)
434       continue;
435 
436     SmallVector<StringRef, 8> Addresses;
437     Token.split(Addresses, "/");
438     uint64_t Src;
439     uint64_t Dst;
440 
441     // Stop at broken LBR records.
442     if (Addresses[0].substr(2).getAsInteger(16, Src) ||
443         Addresses[1].substr(2).getAsInteger(16, Dst)) {
444       WithColor::warning() << "Invalid address in LBR record at line "
445                            << TraceIt.getLineNumber() << ": "
446                            << TraceIt.getCurrentLine() << "\n";
447       break;
448     }
449 
450     bool SrcIsInternal = Binary->addressIsCode(Src);
451     bool DstIsInternal = Binary->addressIsCode(Dst);
452     bool IsExternal = !SrcIsInternal && !DstIsInternal;
453     bool IsIncoming = !SrcIsInternal && DstIsInternal;
454     bool IsOutgoing = SrcIsInternal && !DstIsInternal;
455     bool IsArtificial = false;
456 
457     // Ignore branches outside the current binary.
458     if (IsExternal)
459       continue;
460 
461     if (IsOutgoing) {
462       if (!PrevTrDst) {
463         // This is unpaired outgoing jump which is likely due to interrupt or
464         // incomplete LBR trace. Ignore current and subsequent entries since
465         // they are likely in different contexts.
466         break;
467       }
468 
469       if (Binary->addressIsReturn(Src)) {
470         // In a callback case, a return from internal code, say A, to external
471         // runtime can happen. The external runtime can then call back to
472         // another internal routine, say B. Making an artificial branch that
473         // looks like a return from A to B can confuse the unwinder to treat
474         // the instruction before B as the call instruction.
475         break;
476       }
477 
478       // For transition to external code, group the Source with the next
479       // availabe transition target.
480       Dst = PrevTrDst;
481       PrevTrDst = 0;
482       IsArtificial = true;
483     } else {
484       if (PrevTrDst) {
485         // If we have seen an incoming transition from external code to internal
486         // code, but not a following outgoing transition, the incoming
487         // transition is likely due to interrupt which is usually unpaired.
488         // Ignore current and subsequent entries since they are likely in
489         // different contexts.
490         break;
491       }
492 
493       if (IsIncoming) {
494         // For transition from external code (such as dynamic libraries) to
495         // the current binary, keep track of the branch target which will be
496         // grouped with the Source of the last transition from the current
497         // binary.
498         PrevTrDst = Dst;
499         continue;
500       }
501     }
502 
503     // TODO: filter out buggy duplicate branches on Skylake
504 
505     LBRStack.emplace_back(LBREntry(Src, Dst, IsArtificial));
506   }
507   TraceIt.advance();
508   return !LBRStack.empty();
509 }
510 
511 bool PerfReaderBase::extractCallstack(TraceStream &TraceIt,
512                                       SmallVectorImpl<uint64_t> &CallStack) {
513   // The raw format of call stack is like:
514   //            4005dc      # leaf frame
515   //	          400634
516   //	          400684      # root frame
517   // It's in bottom-up order with each frame in one line.
518 
519   // Extract stack frames from sample
520   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
521     StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
522     uint64_t FrameAddr = 0;
523     if (FrameStr.getAsInteger(16, FrameAddr)) {
524       // We might parse a non-perf sample line like empty line and comments,
525       // skip it
526       TraceIt.advance();
527       return false;
528     }
529     TraceIt.advance();
530     // Currently intermixed frame from different binaries is not supported.
531     // Ignore bottom frames not from binary of interest.
532     if (!Binary->addressIsCode(FrameAddr))
533       break;
534 
535     // We need to translate return address to call address for non-leaf frames.
536     if (!CallStack.empty()) {
537       auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
538       if (!CallAddr) {
539         // Stop at an invalid return address caused by bad unwinding. This could
540         // happen to frame-pointer-based unwinding and the callee functions that
541         // do not have the frame pointer chain set up.
542         InvalidReturnAddresses.insert(FrameAddr);
543         break;
544       }
545       FrameAddr = CallAddr;
546     }
547 
548     CallStack.emplace_back(FrameAddr);
549   }
550 
551   // Skip other unrelated line, find the next valid LBR line
552   // Note that even for empty call stack, we should skip the address at the
553   // bottom, otherwise the following pass may generate a truncated callstack
554   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
555     TraceIt.advance();
556   }
557   // Filter out broken stack sample. We may not have complete frame info
558   // if sample end up in prolog/epilog, the result is dangling context not
559   // connected to entry point. This should be relatively rare thus not much
560   // impact on overall profile quality. However we do want to filter them
561   // out to reduce the number of different calling contexts. One instance
562   // of such case - when sample landed in prolog/epilog, somehow stack
563   // walking will be broken in an unexpected way that higher frames will be
564   // missing.
565   return !CallStack.empty() &&
566          !Binary->addressInPrologEpilog(CallStack.front());
567 }
568 
569 void PerfReaderBase::warnIfMissingMMap() {
570   if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
571     WithColor::warning() << "No relevant mmap event is matched, will use "
572                             "preferred address as the base loading address!\n";
573     // Avoid redundant warning, only warn at the first unmatched sample.
574     Binary->setMissingMMapWarned(true);
575   }
576 }
577 
578 void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
579   // The raw hybird sample started with call stack in FILO order and followed
580   // intermediately by LBR sample
581   // e.g.
582   // 	          4005dc    # call stack leaf
583   //	          400634
584   //	          400684    # call stack root
585   // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
586   //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
587   //
588   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
589 
590   // Parsing call stack and populate into PerfSample.CallStack
591   if (!extractCallstack(TraceIt, Sample->CallStack)) {
592     // Skip the next LBR line matched current call stack
593     if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x"))
594       TraceIt.advance();
595     return;
596   }
597 
598   warnIfMissingMMap();
599 
600   if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x")) {
601     // Parsing LBR stack and populate into PerfSample.LBRStack
602     if (extractLBRStack(TraceIt, Sample->LBRStack)) {
603       // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
604       // ranges
605       Sample->CallStack.front() = Sample->LBRStack[0].Target;
606       // Record samples by aggregation
607       AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
608     }
609   } else {
610     // LBR sample is encoded in single line after stack sample
611     exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
612   }
613 }
614 
615 void PerfReaderBase::writeRawProfile(StringRef Filename) {
616   std::error_code EC;
617   raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
618   if (EC)
619     exitWithError(EC, Filename);
620   writeRawProfile(OS);
621 }
622 
623 void LBRPerfReader::writeRawProfile(raw_fd_ostream &OS) {
624   /*
625      Format:
626      number of entries in RangeCounter
627      from_1-to_1:count_1
628      from_2-to_2:count_2
629      ......
630      from_n-to_n:count_n
631      number of entries in BranchCounter
632      src_1->dst_1:count_1
633      src_2->dst_2:count_2
634      ......
635      src_n->dst_n:count_n
636   */
637 
638   SampleCounter &Counter = SampleCounters.begin()->second;
639   OS << Counter.RangeCounter.size() << "\n";
640   for (auto I : Counter.RangeCounter) {
641     OS << Twine::utohexstr(I.first.first) << "-"
642        << Twine::utohexstr(I.first.second) << ":" << I.second << "\n";
643   }
644 
645   OS << Counter.BranchCounter.size() << "\n";
646   for (auto I : Counter.BranchCounter) {
647     OS << Twine::utohexstr(I.first.first) << "->"
648        << Twine::utohexstr(I.first.second) << ":" << I.second << "\n";
649   }
650 }
651 
652 void LBRPerfReader::computeCounterFromLBR(const PerfSample *Sample,
653                                           uint64_t Repeat) {
654   SampleCounter &Counter = SampleCounters.begin()->second;
655   uint64_t EndOffeset = 0;
656   for (const LBREntry &LBR : Sample->LBRStack) {
657     uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
658     uint64_t TargetOffset = Binary->virtualAddrToOffset(LBR.Target);
659 
660     if (!LBR.IsArtificial) {
661       Counter.recordBranchCount(SourceOffset, TargetOffset, Repeat);
662     }
663 
664     // If this not the first LBR, update the range count between TO of current
665     // LBR and FROM of next LBR.
666     uint64_t StartOffset = TargetOffset;
667     if (EndOffeset != 0)
668       Counter.recordRangeCount(StartOffset, EndOffeset, Repeat);
669     EndOffeset = SourceOffset;
670   }
671 }
672 
673 void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
674   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
675   // Parsing LBR stack and populate into PerfSample.LBRStack
676   if (extractLBRStack(TraceIt, Sample->LBRStack)) {
677     warnIfMissingMMap();
678     // Record LBR only samples by aggregation
679     AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
680   }
681 }
682 
683 void LBRPerfReader::generateRawProfile() {
684   assert(SampleCounters.size() == 1 && "Must have one entry of sample counter");
685   for (const auto &Item : AggregatedSamples) {
686     const PerfSample *Sample = Item.first.getPtr();
687     computeCounterFromLBR(Sample, Item.second);
688   }
689 
690   if (SkipSymbolization)
691     PerfReaderBase::writeRawProfile(OutputFilename);
692 }
693 
694 uint64_t PerfReaderBase::parseAggregatedCount(TraceStream &TraceIt) {
695   // The aggregated count is optional, so do not skip the line and return 1 if
696   // it's unmatched
697   uint64_t Count = 1;
698   if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
699     TraceIt.advance();
700   return Count;
701 }
702 
703 void PerfReaderBase::parseSample(TraceStream &TraceIt) {
704   uint64_t Count = parseAggregatedCount(TraceIt);
705   assert(Count >= 1 && "Aggregated count should be >= 1!");
706   parseSample(TraceIt, Count);
707 }
708 
709 void PerfReaderBase::parseMMap2Event(TraceStream &TraceIt) {
710   // Parse a line like:
711   //  PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
712   //  08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
713   constexpr static const char *const Pattern =
714       "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
715       "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
716       "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
717   // Field 0 - whole line
718   // Field 1 - PID
719   // Field 2 - base address
720   // Field 3 - mmapped size
721   // Field 4 - page offset
722   // Field 5 - binary path
723   enum EventIndex {
724     WHOLE_LINE = 0,
725     PID = 1,
726     MMAPPED_ADDRESS = 2,
727     MMAPPED_SIZE = 3,
728     PAGE_OFFSET = 4,
729     BINARY_PATH = 5
730   };
731 
732   Regex RegMmap2(Pattern);
733   SmallVector<StringRef, 6> Fields;
734   bool R = RegMmap2.match(TraceIt.getCurrentLine(), &Fields);
735   if (!R) {
736     std::string ErrorMsg = "Cannot parse mmap event: Line" +
737                            Twine(TraceIt.getLineNumber()).str() + ": " +
738                            TraceIt.getCurrentLine().str() + " \n";
739     exitWithError(ErrorMsg);
740   }
741   MMapEvent Event;
742   Fields[PID].getAsInteger(10, Event.PID);
743   Fields[MMAPPED_ADDRESS].getAsInteger(0, Event.Address);
744   Fields[MMAPPED_SIZE].getAsInteger(0, Event.Size);
745   Fields[PAGE_OFFSET].getAsInteger(0, Event.Offset);
746   Event.BinaryPath = Fields[BINARY_PATH];
747   updateBinaryAddress(Event);
748   if (ShowMmapEvents) {
749     outs() << "Mmap: Binary " << Event.BinaryPath << " loaded at "
750            << format("0x%" PRIx64 ":", Event.Address) << " \n";
751   }
752   TraceIt.advance();
753 }
754 
755 void PerfReaderBase::parseEventOrSample(TraceStream &TraceIt) {
756   if (TraceIt.getCurrentLine().startswith("PERF_RECORD_MMAP2"))
757     parseMMap2Event(TraceIt);
758   else
759     parseSample(TraceIt);
760 }
761 
762 void PerfReaderBase::parseAndAggregateTrace(StringRef Filename) {
763   // Trace line iterator
764   TraceStream TraceIt(Filename);
765   while (!TraceIt.isAtEoF())
766     parseEventOrSample(TraceIt);
767 }
768 
769 PerfScriptType
770 PerfReaderBase::extractPerfType(cl::list<std::string> &PerfTraceFilenames) {
771   PerfScriptType PerfType = PERF_UNKNOWN;
772   for (auto FileName : PerfTraceFilenames) {
773     PerfScriptType Type = checkPerfScriptType(FileName);
774     if (Type == PERF_INVALID)
775       exitWithError("Invalid perf script input!");
776     if (PerfType != PERF_UNKNOWN && PerfType != Type)
777       exitWithError("Inconsistent sample among different perf scripts");
778     PerfType = Type;
779   }
780   return PerfType;
781 }
782 
783 void HybridPerfReader::generateRawProfile() { unwindSamples(); }
784 
785 void PerfReaderBase::warnTruncatedStack() {
786   for (auto Address : InvalidReturnAddresses) {
787     WithColor::warning()
788         << "Truncated stack sample due to invalid return address at "
789         << format("0x%" PRIx64, Address)
790         << ", likely caused by frame pointer omission\n";
791   }
792 }
793 
794 void PerfReaderBase::parsePerfTraces(
795     cl::list<std::string> &PerfTraceFilenames) {
796   // Parse perf traces and do aggregation.
797   for (auto Filename : PerfTraceFilenames)
798     parseAndAggregateTrace(Filename);
799 
800   warnTruncatedStack();
801   generateRawProfile();
802 }
803 
804 } // end namespace sampleprof
805 } // end namespace llvm
806