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