PerfReader.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. //===-- PerfReader.h - 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. #ifndef LLVM_TOOLS_LLVM_PROFGEN_PERFREADER_H
  9. #define LLVM_TOOLS_LLVM_PROFGEN_PERFREADER_H
  10. #include "ErrorHandling.h"
  11. #include "ProfiledBinary.h"
  12. #include "llvm/Support/Casting.h"
  13. #include "llvm/Support/CommandLine.h"
  14. #include "llvm/Support/Regex.h"
  15. #include <cstdint>
  16. #include <fstream>
  17. #include <list>
  18. #include <map>
  19. #include <vector>
  20. using namespace llvm;
  21. using namespace sampleprof;
  22. namespace llvm {
  23. namespace sampleprof {
  24. // Stream based trace line iterator
  25. class TraceStream {
  26. std::string CurrentLine;
  27. std::ifstream Fin;
  28. bool IsAtEoF = false;
  29. uint64_t LineNumber = 0;
  30. public:
  31. TraceStream(StringRef Filename) : Fin(Filename.str()) {
  32. if (!Fin.good())
  33. exitWithError("Error read input perf script file", Filename);
  34. advance();
  35. }
  36. StringRef getCurrentLine() {
  37. assert(!IsAtEoF && "Line iterator reaches the End-of-File!");
  38. return CurrentLine;
  39. }
  40. uint64_t getLineNumber() { return LineNumber; }
  41. bool isAtEoF() { return IsAtEoF; }
  42. // Read the next line
  43. void advance() {
  44. if (!std::getline(Fin, CurrentLine)) {
  45. IsAtEoF = true;
  46. return;
  47. }
  48. LineNumber++;
  49. }
  50. };
  51. // The type of input format.
  52. enum PerfFormat {
  53. UnknownFormat = 0,
  54. PerfData = 1, // Raw linux perf.data.
  55. PerfScript = 2, // Perf script create by `perf script` command.
  56. UnsymbolizedProfile = 3, // Unsymbolized profile generated by llvm-profgen.
  57. };
  58. // The type of perfscript content.
  59. enum PerfContent {
  60. UnknownContent = 0,
  61. LBR = 1, // Only LBR sample.
  62. LBRStack = 2, // Hybrid sample including call stack and LBR stack.
  63. };
  64. struct PerfInputFile {
  65. std::string InputFile;
  66. PerfFormat Format = PerfFormat::UnknownFormat;
  67. PerfContent Content = PerfContent::UnknownContent;
  68. };
  69. // The parsed LBR sample entry.
  70. struct LBREntry {
  71. uint64_t Source = 0;
  72. uint64_t Target = 0;
  73. LBREntry(uint64_t S, uint64_t T) : Source(S), Target(T) {}
  74. #ifndef NDEBUG
  75. void print() const {
  76. dbgs() << "from " << format("%#010x", Source) << " to "
  77. << format("%#010x", Target);
  78. }
  79. #endif
  80. };
  81. #ifndef NDEBUG
  82. static inline void printLBRStack(const SmallVectorImpl<LBREntry> &LBRStack) {
  83. for (size_t I = 0; I < LBRStack.size(); I++) {
  84. dbgs() << "[" << I << "] ";
  85. LBRStack[I].print();
  86. dbgs() << "\n";
  87. }
  88. }
  89. static inline void printCallStack(const SmallVectorImpl<uint64_t> &CallStack) {
  90. for (size_t I = 0; I < CallStack.size(); I++) {
  91. dbgs() << "[" << I << "] " << format("%#010x", CallStack[I]) << "\n";
  92. }
  93. }
  94. #endif
  95. // Hash interface for generic data of type T
  96. // Data should implement a \fn getHashCode and a \fn isEqual
  97. // Currently getHashCode is non-virtual to avoid the overhead of calling vtable,
  98. // i.e we explicitly calculate hash of derived class, assign to base class's
  99. // HashCode. This also provides the flexibility for calculating the hash code
  100. // incrementally(like rolling hash) during frame stack unwinding since unwinding
  101. // only changes the leaf of frame stack. \fn isEqual is a virtual function,
  102. // which will have perf overhead. In the future, if we redesign a better hash
  103. // function, then we can just skip this or switch to non-virtual function(like
  104. // just ignore comparison if hash conflicts probabilities is low)
  105. template <class T> class Hashable {
  106. public:
  107. std::shared_ptr<T> Data;
  108. Hashable(const std::shared_ptr<T> &D) : Data(D) {}
  109. // Hash code generation
  110. struct Hash {
  111. uint64_t operator()(const Hashable<T> &Key) const {
  112. // Don't make it virtual for getHashCode
  113. uint64_t Hash = Key.Data->getHashCode();
  114. assert(Hash && "Should generate HashCode for it!");
  115. return Hash;
  116. }
  117. };
  118. // Hash equal
  119. struct Equal {
  120. bool operator()(const Hashable<T> &LHS, const Hashable<T> &RHS) const {
  121. // Precisely compare the data, vtable will have overhead.
  122. return LHS.Data->isEqual(RHS.Data.get());
  123. }
  124. };
  125. T *getPtr() const { return Data.get(); }
  126. };
  127. struct PerfSample {
  128. // LBR stack recorded in FIFO order.
  129. SmallVector<LBREntry, 16> LBRStack;
  130. // Call stack recorded in FILO(leaf to root) order, it's used for CS-profile
  131. // generation
  132. SmallVector<uint64_t, 16> CallStack;
  133. virtual ~PerfSample() = default;
  134. uint64_t getHashCode() const {
  135. // Use simple DJB2 hash
  136. auto HashCombine = [](uint64_t H, uint64_t V) {
  137. return ((H << 5) + H) + V;
  138. };
  139. uint64_t Hash = 5381;
  140. for (const auto &Value : CallStack) {
  141. Hash = HashCombine(Hash, Value);
  142. }
  143. for (const auto &Entry : LBRStack) {
  144. Hash = HashCombine(Hash, Entry.Source);
  145. Hash = HashCombine(Hash, Entry.Target);
  146. }
  147. return Hash;
  148. }
  149. bool isEqual(const PerfSample *Other) const {
  150. const SmallVector<uint64_t, 16> &OtherCallStack = Other->CallStack;
  151. const SmallVector<LBREntry, 16> &OtherLBRStack = Other->LBRStack;
  152. if (CallStack.size() != OtherCallStack.size() ||
  153. LBRStack.size() != OtherLBRStack.size())
  154. return false;
  155. if (!std::equal(CallStack.begin(), CallStack.end(), OtherCallStack.begin()))
  156. return false;
  157. for (size_t I = 0; I < OtherLBRStack.size(); I++) {
  158. if (LBRStack[I].Source != OtherLBRStack[I].Source ||
  159. LBRStack[I].Target != OtherLBRStack[I].Target)
  160. return false;
  161. }
  162. return true;
  163. }
  164. #ifndef NDEBUG
  165. uint64_t Linenum = 0;
  166. void print() const {
  167. dbgs() << "Line " << Linenum << "\n";
  168. dbgs() << "LBR stack\n";
  169. printLBRStack(LBRStack);
  170. dbgs() << "Call stack\n";
  171. printCallStack(CallStack);
  172. }
  173. #endif
  174. };
  175. // After parsing the sample, we record the samples by aggregating them
  176. // into this counter. The key stores the sample data and the value is
  177. // the sample repeat times.
  178. using AggregatedCounter =
  179. std::unordered_map<Hashable<PerfSample>, uint64_t,
  180. Hashable<PerfSample>::Hash, Hashable<PerfSample>::Equal>;
  181. using SampleVector = SmallVector<std::tuple<uint64_t, uint64_t, uint64_t>, 16>;
  182. inline bool isValidFallThroughRange(uint64_t Start, uint64_t End,
  183. ProfiledBinary *Binary) {
  184. // Start bigger than End is considered invalid.
  185. // LBR ranges cross the unconditional jmp are also assumed invalid.
  186. // It's found that perf data may contain duplicate LBR entries that could form
  187. // a range that does not reflect real execution flow on some Intel targets,
  188. // e.g. Skylake. Such ranges are ususally very long. Exclude them since there
  189. // cannot be a linear execution range that spans over unconditional jmp.
  190. return Start <= End && !Binary->rangeCrossUncondBranch(Start, End);
  191. }
  192. // The state for the unwinder, it doesn't hold the data but only keep the
  193. // pointer/index of the data, While unwinding, the CallStack is changed
  194. // dynamicially and will be recorded as the context of the sample
  195. struct UnwindState {
  196. // Profiled binary that current frame address belongs to
  197. const ProfiledBinary *Binary;
  198. // Call stack trie node
  199. struct ProfiledFrame {
  200. const uint64_t Address = DummyRoot;
  201. ProfiledFrame *Parent;
  202. SampleVector RangeSamples;
  203. SampleVector BranchSamples;
  204. std::unordered_map<uint64_t, std::unique_ptr<ProfiledFrame>> Children;
  205. ProfiledFrame(uint64_t Addr = 0, ProfiledFrame *P = nullptr)
  206. : Address(Addr), Parent(P) {}
  207. ProfiledFrame *getOrCreateChildFrame(uint64_t Address) {
  208. assert(Address && "Address can't be zero!");
  209. auto Ret = Children.emplace(
  210. Address, std::make_unique<ProfiledFrame>(Address, this));
  211. return Ret.first->second.get();
  212. }
  213. void recordRangeCount(uint64_t Start, uint64_t End, uint64_t Count) {
  214. RangeSamples.emplace_back(std::make_tuple(Start, End, Count));
  215. }
  216. void recordBranchCount(uint64_t Source, uint64_t Target, uint64_t Count) {
  217. BranchSamples.emplace_back(std::make_tuple(Source, Target, Count));
  218. }
  219. bool isDummyRoot() { return Address == DummyRoot; }
  220. bool isExternalFrame() { return Address == ExternalAddr; }
  221. bool isLeafFrame() { return Children.empty(); }
  222. };
  223. ProfiledFrame DummyTrieRoot;
  224. ProfiledFrame *CurrentLeafFrame;
  225. // Used to fall through the LBR stack
  226. uint32_t LBRIndex = 0;
  227. // Reference to PerfSample.LBRStack
  228. const SmallVector<LBREntry, 16> &LBRStack;
  229. // Used to iterate the address range
  230. InstructionPointer InstPtr;
  231. // Indicate whether unwinding is currently in a bad state which requires to
  232. // skip all subsequent unwinding.
  233. bool Invalid = false;
  234. UnwindState(const PerfSample *Sample, const ProfiledBinary *Binary)
  235. : Binary(Binary), LBRStack(Sample->LBRStack),
  236. InstPtr(Binary, Sample->CallStack.front()) {
  237. initFrameTrie(Sample->CallStack);
  238. }
  239. bool validateInitialState() {
  240. uint64_t LBRLeaf = LBRStack[LBRIndex].Target;
  241. uint64_t LeafAddr = CurrentLeafFrame->Address;
  242. assert((LBRLeaf != ExternalAddr || LBRLeaf == LeafAddr) &&
  243. "External leading LBR should match the leaf frame.");
  244. // When we take a stack sample, ideally the sampling distance between the
  245. // leaf IP of stack and the last LBR target shouldn't be very large.
  246. // Use a heuristic size (0x100) to filter out broken records.
  247. if (LeafAddr < LBRLeaf || LeafAddr - LBRLeaf >= 0x100) {
  248. WithColor::warning() << "Bogus trace: stack tip = "
  249. << format("%#010x", LeafAddr)
  250. << ", LBR tip = " << format("%#010x\n", LBRLeaf);
  251. return false;
  252. }
  253. return true;
  254. }
  255. void checkStateConsistency() {
  256. assert(InstPtr.Address == CurrentLeafFrame->Address &&
  257. "IP should align with context leaf");
  258. }
  259. void setInvalid() { Invalid = true; }
  260. bool hasNextLBR() const { return LBRIndex < LBRStack.size(); }
  261. uint64_t getCurrentLBRSource() const { return LBRStack[LBRIndex].Source; }
  262. uint64_t getCurrentLBRTarget() const { return LBRStack[LBRIndex].Target; }
  263. const LBREntry &getCurrentLBR() const { return LBRStack[LBRIndex]; }
  264. bool IsLastLBR() const { return LBRIndex == 0; }
  265. bool getLBRStackSize() const { return LBRStack.size(); }
  266. void advanceLBR() { LBRIndex++; }
  267. ProfiledFrame *getParentFrame() { return CurrentLeafFrame->Parent; }
  268. void pushFrame(uint64_t Address) {
  269. CurrentLeafFrame = CurrentLeafFrame->getOrCreateChildFrame(Address);
  270. }
  271. void switchToFrame(uint64_t Address) {
  272. if (CurrentLeafFrame->Address == Address)
  273. return;
  274. CurrentLeafFrame = CurrentLeafFrame->Parent->getOrCreateChildFrame(Address);
  275. }
  276. void popFrame() { CurrentLeafFrame = CurrentLeafFrame->Parent; }
  277. void clearCallStack() { CurrentLeafFrame = &DummyTrieRoot; }
  278. void initFrameTrie(const SmallVectorImpl<uint64_t> &CallStack) {
  279. ProfiledFrame *Cur = &DummyTrieRoot;
  280. for (auto Address : reverse(CallStack)) {
  281. Cur = Cur->getOrCreateChildFrame(Address);
  282. }
  283. CurrentLeafFrame = Cur;
  284. }
  285. ProfiledFrame *getDummyRootPtr() { return &DummyTrieRoot; }
  286. };
  287. // Base class for sample counter key with context
  288. struct ContextKey {
  289. uint64_t HashCode = 0;
  290. virtual ~ContextKey() = default;
  291. uint64_t getHashCode() {
  292. if (HashCode == 0)
  293. genHashCode();
  294. return HashCode;
  295. }
  296. virtual void genHashCode() = 0;
  297. virtual bool isEqual(const ContextKey *K) const {
  298. return HashCode == K->HashCode;
  299. };
  300. // Utilities for LLVM-style RTTI
  301. enum ContextKind { CK_StringBased, CK_AddrBased };
  302. const ContextKind Kind;
  303. ContextKind getKind() const { return Kind; }
  304. ContextKey(ContextKind K) : Kind(K){};
  305. };
  306. // String based context id
  307. struct StringBasedCtxKey : public ContextKey {
  308. SampleContextFrameVector Context;
  309. bool WasLeafInlined;
  310. StringBasedCtxKey() : ContextKey(CK_StringBased), WasLeafInlined(false){};
  311. static bool classof(const ContextKey *K) {
  312. return K->getKind() == CK_StringBased;
  313. }
  314. bool isEqual(const ContextKey *K) const override {
  315. const StringBasedCtxKey *Other = dyn_cast<StringBasedCtxKey>(K);
  316. return Context == Other->Context;
  317. }
  318. void genHashCode() override {
  319. HashCode = hash_value(SampleContextFrames(Context));
  320. }
  321. };
  322. // Address-based context id
  323. struct AddrBasedCtxKey : public ContextKey {
  324. SmallVector<uint64_t, 16> Context;
  325. bool WasLeafInlined;
  326. AddrBasedCtxKey() : ContextKey(CK_AddrBased), WasLeafInlined(false){};
  327. static bool classof(const ContextKey *K) {
  328. return K->getKind() == CK_AddrBased;
  329. }
  330. bool isEqual(const ContextKey *K) const override {
  331. const AddrBasedCtxKey *Other = dyn_cast<AddrBasedCtxKey>(K);
  332. return Context == Other->Context;
  333. }
  334. void genHashCode() override {
  335. HashCode = hash_combine_range(Context.begin(), Context.end());
  336. }
  337. };
  338. // The counter of branch samples for one function indexed by the branch,
  339. // which is represented as the source and target offset pair.
  340. using BranchSample = std::map<std::pair<uint64_t, uint64_t>, uint64_t>;
  341. // The counter of range samples for one function indexed by the range,
  342. // which is represented as the start and end offset pair.
  343. using RangeSample = std::map<std::pair<uint64_t, uint64_t>, uint64_t>;
  344. // Wrapper for sample counters including range counter and branch counter
  345. struct SampleCounter {
  346. RangeSample RangeCounter;
  347. BranchSample BranchCounter;
  348. void recordRangeCount(uint64_t Start, uint64_t End, uint64_t Repeat) {
  349. assert(Start <= End && "Invalid instruction range");
  350. RangeCounter[{Start, End}] += Repeat;
  351. }
  352. void recordBranchCount(uint64_t Source, uint64_t Target, uint64_t Repeat) {
  353. BranchCounter[{Source, Target}] += Repeat;
  354. }
  355. };
  356. // Sample counter with context to support context-sensitive profile
  357. using ContextSampleCounterMap =
  358. std::unordered_map<Hashable<ContextKey>, SampleCounter,
  359. Hashable<ContextKey>::Hash, Hashable<ContextKey>::Equal>;
  360. struct FrameStack {
  361. SmallVector<uint64_t, 16> Stack;
  362. ProfiledBinary *Binary;
  363. FrameStack(ProfiledBinary *B) : Binary(B) {}
  364. bool pushFrame(UnwindState::ProfiledFrame *Cur) {
  365. assert(!Cur->isExternalFrame() &&
  366. "External frame's not expected for context stack.");
  367. Stack.push_back(Cur->Address);
  368. return true;
  369. }
  370. void popFrame() {
  371. if (!Stack.empty())
  372. Stack.pop_back();
  373. }
  374. std::shared_ptr<StringBasedCtxKey> getContextKey();
  375. };
  376. struct AddressStack {
  377. SmallVector<uint64_t, 16> Stack;
  378. ProfiledBinary *Binary;
  379. AddressStack(ProfiledBinary *B) : Binary(B) {}
  380. bool pushFrame(UnwindState::ProfiledFrame *Cur) {
  381. assert(!Cur->isExternalFrame() &&
  382. "External frame's not expected for context stack.");
  383. Stack.push_back(Cur->Address);
  384. return true;
  385. }
  386. void popFrame() {
  387. if (!Stack.empty())
  388. Stack.pop_back();
  389. }
  390. std::shared_ptr<AddrBasedCtxKey> getContextKey();
  391. };
  392. /*
  393. As in hybrid sample we have a group of LBRs and the most recent sampling call
  394. stack, we can walk through those LBRs to infer more call stacks which would be
  395. used as context for profile. VirtualUnwinder is the class to do the call stack
  396. unwinding based on LBR state. Two types of unwinding are processd here:
  397. 1) LBR unwinding and 2) linear range unwinding.
  398. Specifically, for each LBR entry(can be classified into call, return, regular
  399. branch), LBR unwinding will replay the operation by pushing, popping or
  400. switching leaf frame towards the call stack and since the initial call stack
  401. is most recently sampled, the replay should be in anti-execution order, i.e. for
  402. the regular case, pop the call stack when LBR is call, push frame on call stack
  403. when LBR is return. After each LBR processed, it also needs to align with the
  404. next LBR by going through instructions from previous LBR's target to current
  405. LBR's source, which is the linear unwinding. As instruction from linear range
  406. can come from different function by inlining, linear unwinding will do the range
  407. splitting and record counters by the range with same inline context. Over those
  408. unwinding process we will record each call stack as context id and LBR/linear
  409. range as sample counter for further CS profile generation.
  410. */
  411. class VirtualUnwinder {
  412. public:
  413. VirtualUnwinder(ContextSampleCounterMap *Counter, ProfiledBinary *B)
  414. : CtxCounterMap(Counter), Binary(B) {}
  415. bool unwind(const PerfSample *Sample, uint64_t Repeat);
  416. std::set<uint64_t> &getUntrackedCallsites() { return UntrackedCallsites; }
  417. uint64_t NumTotalBranches = 0;
  418. uint64_t NumExtCallBranch = 0;
  419. uint64_t NumMissingExternalFrame = 0;
  420. uint64_t NumMismatchedProEpiBranch = 0;
  421. uint64_t NumMismatchedExtCallBranch = 0;
  422. uint64_t NumUnpairedExtAddr = 0;
  423. uint64_t NumPairedExtAddr = 0;
  424. private:
  425. bool isSourceExternal(UnwindState &State) const {
  426. return State.getCurrentLBRSource() == ExternalAddr;
  427. }
  428. bool isTargetExternal(UnwindState &State) const {
  429. return State.getCurrentLBRTarget() == ExternalAddr;
  430. }
  431. // Determine whether the return source is from external code by checking if
  432. // the target's the next inst is a call inst.
  433. bool isReturnFromExternal(UnwindState &State) const {
  434. return isSourceExternal(State) &&
  435. (Binary->getCallAddrFromFrameAddr(State.getCurrentLBRTarget()) != 0);
  436. }
  437. // If the source is external address but it's not the `return` case, treat it
  438. // as a call from external.
  439. bool isCallFromExternal(UnwindState &State) const {
  440. return isSourceExternal(State) &&
  441. Binary->getCallAddrFromFrameAddr(State.getCurrentLBRTarget()) == 0;
  442. }
  443. bool isCallState(UnwindState &State) const {
  444. // The tail call frame is always missing here in stack sample, we will
  445. // use a specific tail call tracker to infer it.
  446. if (!isValidState(State))
  447. return false;
  448. if (Binary->addressIsCall(State.getCurrentLBRSource()))
  449. return true;
  450. return isCallFromExternal(State);
  451. }
  452. bool isReturnState(UnwindState &State) const {
  453. if (!isValidState(State))
  454. return false;
  455. // Simply check addressIsReturn, as ret is always reliable, both for
  456. // regular call and tail call.
  457. if (Binary->addressIsReturn(State.getCurrentLBRSource()))
  458. return true;
  459. return isReturnFromExternal(State);
  460. }
  461. bool isValidState(UnwindState &State) const { return !State.Invalid; }
  462. void unwindCall(UnwindState &State);
  463. void unwindLinear(UnwindState &State, uint64_t Repeat);
  464. void unwindReturn(UnwindState &State);
  465. void unwindBranch(UnwindState &State);
  466. template <typename T>
  467. void collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur, T &Stack);
  468. // Collect each samples on trie node by DFS traversal
  469. template <typename T>
  470. void collectSamplesFromFrameTrie(UnwindState::ProfiledFrame *Cur, T &Stack);
  471. void collectSamplesFromFrameTrie(UnwindState::ProfiledFrame *Cur);
  472. void recordRangeCount(uint64_t Start, uint64_t End, UnwindState &State,
  473. uint64_t Repeat);
  474. void recordBranchCount(const LBREntry &Branch, UnwindState &State,
  475. uint64_t Repeat);
  476. ContextSampleCounterMap *CtxCounterMap;
  477. // Profiled binary that current frame address belongs to
  478. ProfiledBinary *Binary;
  479. // Keep track of all untracked callsites
  480. std::set<uint64_t> UntrackedCallsites;
  481. };
  482. // Read perf trace to parse the events and samples.
  483. class PerfReaderBase {
  484. public:
  485. PerfReaderBase(ProfiledBinary *B, StringRef PerfTrace)
  486. : Binary(B), PerfTraceFile(PerfTrace) {
  487. // Initialize the base address to preferred address.
  488. Binary->setBaseAddress(Binary->getPreferredBaseAddress());
  489. };
  490. virtual ~PerfReaderBase() = default;
  491. static std::unique_ptr<PerfReaderBase>
  492. create(ProfiledBinary *Binary, PerfInputFile &PerfInput,
  493. std::optional<uint32_t> PIDFilter);
  494. // Entry of the reader to parse multiple perf traces
  495. virtual void parsePerfTraces() = 0;
  496. const ContextSampleCounterMap &getSampleCounters() const {
  497. return SampleCounters;
  498. }
  499. bool profileIsCS() { return ProfileIsCS; }
  500. protected:
  501. ProfiledBinary *Binary = nullptr;
  502. StringRef PerfTraceFile;
  503. ContextSampleCounterMap SampleCounters;
  504. bool ProfileIsCS = false;
  505. uint64_t NumTotalSample = 0;
  506. uint64_t NumLeafExternalFrame = 0;
  507. uint64_t NumLeadingOutgoingLBR = 0;
  508. };
  509. // Read perf script to parse the events and samples.
  510. class PerfScriptReader : public PerfReaderBase {
  511. public:
  512. PerfScriptReader(ProfiledBinary *B, StringRef PerfTrace,
  513. std::optional<uint32_t> PID)
  514. : PerfReaderBase(B, PerfTrace), PIDFilter(PID){};
  515. // Entry of the reader to parse multiple perf traces
  516. void parsePerfTraces() override;
  517. // Generate perf script from perf data
  518. static PerfInputFile
  519. convertPerfDataToTrace(ProfiledBinary *Binary, PerfInputFile &File,
  520. std::optional<uint32_t> PIDFilter);
  521. // Extract perf script type by peaking at the input
  522. static PerfContent checkPerfScriptType(StringRef FileName);
  523. protected:
  524. // The parsed MMap event
  525. struct MMapEvent {
  526. uint64_t PID = 0;
  527. uint64_t Address = 0;
  528. uint64_t Size = 0;
  529. uint64_t Offset = 0;
  530. StringRef BinaryPath;
  531. };
  532. // Check whether a given line is LBR sample
  533. static bool isLBRSample(StringRef Line);
  534. // Check whether a given line is MMAP event
  535. static bool isMMap2Event(StringRef Line);
  536. // Parse a single line of a PERF_RECORD_MMAP2 event looking for a
  537. // mapping between the binary name and its memory layout.
  538. static bool extractMMap2EventForBinary(ProfiledBinary *Binary, StringRef Line,
  539. MMapEvent &MMap);
  540. // Update base address based on mmap events
  541. void updateBinaryAddress(const MMapEvent &Event);
  542. // Parse mmap event and update binary address
  543. void parseMMap2Event(TraceStream &TraceIt);
  544. // Parse perf events/samples and do aggregation
  545. void parseAndAggregateTrace();
  546. // Parse either an MMAP event or a perf sample
  547. void parseEventOrSample(TraceStream &TraceIt);
  548. // Warn if the relevant mmap event is missing.
  549. void warnIfMissingMMap();
  550. // Emit accumulate warnings.
  551. void warnTruncatedStack();
  552. // Warn if range is invalid.
  553. void warnInvalidRange();
  554. // Extract call stack from the perf trace lines
  555. bool extractCallstack(TraceStream &TraceIt,
  556. SmallVectorImpl<uint64_t> &CallStack);
  557. // Extract LBR stack from one perf trace line
  558. bool extractLBRStack(TraceStream &TraceIt,
  559. SmallVectorImpl<LBREntry> &LBRStack);
  560. uint64_t parseAggregatedCount(TraceStream &TraceIt);
  561. // Parse one sample from multiple perf lines, override this for different
  562. // sample type
  563. void parseSample(TraceStream &TraceIt);
  564. // An aggregated count is given to indicate how many times the sample is
  565. // repeated.
  566. virtual void parseSample(TraceStream &TraceIt, uint64_t Count){};
  567. void computeCounterFromLBR(const PerfSample *Sample, uint64_t Repeat);
  568. // Post process the profile after trace aggregation, we will do simple range
  569. // overlap computation for AutoFDO, or unwind for CSSPGO(hybrid sample).
  570. virtual void generateUnsymbolizedProfile();
  571. void writeUnsymbolizedProfile(StringRef Filename);
  572. void writeUnsymbolizedProfile(raw_fd_ostream &OS);
  573. // Samples with the repeating time generated by the perf reader
  574. AggregatedCounter AggregatedSamples;
  575. // Keep track of all invalid return addresses
  576. std::set<uint64_t> InvalidReturnAddresses;
  577. // PID for the process of interest
  578. std::optional<uint32_t> PIDFilter;
  579. };
  580. /*
  581. The reader of LBR only perf script.
  582. A typical LBR sample is like:
  583. 40062f 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  584. ... 0x4005c8/0x4005dc/P/-/-/0
  585. */
  586. class LBRPerfReader : public PerfScriptReader {
  587. public:
  588. LBRPerfReader(ProfiledBinary *Binary, StringRef PerfTrace,
  589. std::optional<uint32_t> PID)
  590. : PerfScriptReader(Binary, PerfTrace, PID){};
  591. // Parse the LBR only sample.
  592. void parseSample(TraceStream &TraceIt, uint64_t Count) override;
  593. };
  594. /*
  595. Hybrid perf script includes a group of hybrid samples(LBRs + call stack),
  596. which is used to generate CS profile. An example of hybrid sample:
  597. 4005dc # call stack leaf
  598. 400634
  599. 400684 # call stack root
  600. 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  601. ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
  602. */
  603. class HybridPerfReader : public PerfScriptReader {
  604. public:
  605. HybridPerfReader(ProfiledBinary *Binary, StringRef PerfTrace,
  606. std::optional<uint32_t> PID)
  607. : PerfScriptReader(Binary, PerfTrace, PID){};
  608. // Parse the hybrid sample including the call and LBR line
  609. void parseSample(TraceStream &TraceIt, uint64_t Count) override;
  610. void generateUnsymbolizedProfile() override;
  611. private:
  612. // Unwind the hybrid samples after aggregration
  613. void unwindSamples();
  614. };
  615. /*
  616. Format of unsymbolized profile:
  617. [frame1 @ frame2 @ ...] # If it's a CS profile
  618. number of entries in RangeCounter
  619. from_1-to_1:count_1
  620. from_2-to_2:count_2
  621. ......
  622. from_n-to_n:count_n
  623. number of entries in BranchCounter
  624. src_1->dst_1:count_1
  625. src_2->dst_2:count_2
  626. ......
  627. src_n->dst_n:count_n
  628. [frame1 @ frame2 @ ...] # Next context
  629. ......
  630. Note that non-CS profile doesn't have the empty `[]` context.
  631. */
  632. class UnsymbolizedProfileReader : public PerfReaderBase {
  633. public:
  634. UnsymbolizedProfileReader(ProfiledBinary *Binary, StringRef PerfTrace)
  635. : PerfReaderBase(Binary, PerfTrace){};
  636. void parsePerfTraces() override;
  637. private:
  638. void readSampleCounters(TraceStream &TraceIt, SampleCounter &SCounters);
  639. void readUnsymbolizedProfile(StringRef Filename);
  640. std::unordered_set<std::string> ContextStrSet;
  641. };
  642. } // end namespace sampleprof
  643. } // end namespace llvm
  644. #endif