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