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