PerfReader.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. // An artificial branch stands for a series of consecutive branches starting
  74. // from the current binary with a transition through external code and
  75. // eventually landing back in the current binary.
  76. bool IsArtificial = false;
  77. LBREntry(uint64_t S, uint64_t T, bool I)
  78. : Source(S), Target(T), IsArtificial(I) {}
  79. #ifndef NDEBUG
  80. void print() const {
  81. dbgs() << "from " << format("%#010x", Source) << " to "
  82. << format("%#010x", Target);
  83. if (IsArtificial)
  84. dbgs() << " Artificial";
  85. }
  86. #endif
  87. };
  88. #ifndef NDEBUG
  89. static inline void printLBRStack(const SmallVectorImpl<LBREntry> &LBRStack) {
  90. for (size_t I = 0; I < LBRStack.size(); I++) {
  91. dbgs() << "[" << I << "] ";
  92. LBRStack[I].print();
  93. dbgs() << "\n";
  94. }
  95. }
  96. static inline void printCallStack(const SmallVectorImpl<uint64_t> &CallStack) {
  97. for (size_t I = 0; I < CallStack.size(); I++) {
  98. dbgs() << "[" << I << "] " << format("%#010x", CallStack[I]) << "\n";
  99. }
  100. }
  101. #endif
  102. // Hash interface for generic data of type T
  103. // Data should implement a \fn getHashCode and a \fn isEqual
  104. // Currently getHashCode is non-virtual to avoid the overhead of calling vtable,
  105. // i.e we explicitly calculate hash of derived class, assign to base class's
  106. // HashCode. This also provides the flexibility for calculating the hash code
  107. // incrementally(like rolling hash) during frame stack unwinding since unwinding
  108. // only changes the leaf of frame stack. \fn isEqual is a virtual function,
  109. // which will have perf overhead. In the future, if we redesign a better hash
  110. // function, then we can just skip this or switch to non-virtual function(like
  111. // just ignore comparision if hash conflicts probabilities is low)
  112. template <class T> class Hashable {
  113. public:
  114. std::shared_ptr<T> Data;
  115. Hashable(const std::shared_ptr<T> &D) : Data(D) {}
  116. // Hash code generation
  117. struct Hash {
  118. uint64_t operator()(const Hashable<T> &Key) const {
  119. // Don't make it virtual for getHashCode
  120. uint64_t Hash = Key.Data->getHashCode();
  121. assert(Hash && "Should generate HashCode for it!");
  122. return Hash;
  123. }
  124. };
  125. // Hash equal
  126. struct Equal {
  127. bool operator()(const Hashable<T> &LHS, const Hashable<T> &RHS) const {
  128. // Precisely compare the data, vtable will have overhead.
  129. return LHS.Data->isEqual(RHS.Data.get());
  130. }
  131. };
  132. T *getPtr() const { return Data.get(); }
  133. };
  134. struct PerfSample {
  135. // LBR stack recorded in FIFO order.
  136. SmallVector<LBREntry, 16> LBRStack;
  137. // Call stack recorded in FILO(leaf to root) order, it's used for CS-profile
  138. // generation
  139. SmallVector<uint64_t, 16> CallStack;
  140. virtual ~PerfSample() = default;
  141. uint64_t getHashCode() const {
  142. // Use simple DJB2 hash
  143. auto HashCombine = [](uint64_t H, uint64_t V) {
  144. return ((H << 5) + H) + V;
  145. };
  146. uint64_t Hash = 5381;
  147. for (const auto &Value : CallStack) {
  148. Hash = HashCombine(Hash, Value);
  149. }
  150. for (const auto &Entry : LBRStack) {
  151. Hash = HashCombine(Hash, Entry.Source);
  152. Hash = HashCombine(Hash, Entry.Target);
  153. }
  154. return Hash;
  155. }
  156. bool isEqual(const PerfSample *Other) const {
  157. const SmallVector<uint64_t, 16> &OtherCallStack = Other->CallStack;
  158. const SmallVector<LBREntry, 16> &OtherLBRStack = Other->LBRStack;
  159. if (CallStack.size() != OtherCallStack.size() ||
  160. LBRStack.size() != OtherLBRStack.size())
  161. return false;
  162. if (!std::equal(CallStack.begin(), CallStack.end(), OtherCallStack.begin()))
  163. return false;
  164. for (size_t I = 0; I < OtherLBRStack.size(); I++) {
  165. if (LBRStack[I].Source != OtherLBRStack[I].Source ||
  166. LBRStack[I].Target != OtherLBRStack[I].Target)
  167. return false;
  168. }
  169. return true;
  170. }
  171. #ifndef NDEBUG
  172. void print() const {
  173. dbgs() << "LBR stack\n";
  174. printLBRStack(LBRStack);
  175. dbgs() << "Call stack\n";
  176. printCallStack(CallStack);
  177. }
  178. #endif
  179. };
  180. // After parsing the sample, we record the samples by aggregating them
  181. // into this counter. The key stores the sample data and the value is
  182. // the sample repeat times.
  183. using AggregatedCounter =
  184. std::unordered_map<Hashable<PerfSample>, uint64_t,
  185. Hashable<PerfSample>::Hash, Hashable<PerfSample>::Equal>;
  186. using SampleVector = SmallVector<std::tuple<uint64_t, uint64_t, uint64_t>, 16>;
  187. // The state for the unwinder, it doesn't hold the data but only keep the
  188. // pointer/index of the data, While unwinding, the CallStack is changed
  189. // dynamicially and will be recorded as the context of the sample
  190. struct UnwindState {
  191. // Profiled binary that current frame address belongs to
  192. const ProfiledBinary *Binary;
  193. // Call stack trie node
  194. struct ProfiledFrame {
  195. const uint64_t Address = DummyRoot;
  196. ProfiledFrame *Parent;
  197. SampleVector RangeSamples;
  198. SampleVector BranchSamples;
  199. std::unordered_map<uint64_t, std::unique_ptr<ProfiledFrame>> Children;
  200. ProfiledFrame(uint64_t Addr = 0, ProfiledFrame *P = nullptr)
  201. : Address(Addr), Parent(P) {}
  202. ProfiledFrame *getOrCreateChildFrame(uint64_t Address) {
  203. assert(Address && "Address can't be zero!");
  204. auto Ret = Children.emplace(
  205. Address, std::make_unique<ProfiledFrame>(Address, this));
  206. return Ret.first->second.get();
  207. }
  208. void recordRangeCount(uint64_t Start, uint64_t End, uint64_t Count) {
  209. RangeSamples.emplace_back(std::make_tuple(Start, End, Count));
  210. }
  211. void recordBranchCount(uint64_t Source, uint64_t Target, uint64_t Count) {
  212. BranchSamples.emplace_back(std::make_tuple(Source, Target, Count));
  213. }
  214. bool isDummyRoot() { return Address == DummyRoot; }
  215. bool isExternalFrame() { return Address == ExternalAddr; }
  216. bool isLeafFrame() { return Children.empty(); }
  217. };
  218. ProfiledFrame DummyTrieRoot;
  219. ProfiledFrame *CurrentLeafFrame;
  220. // Used to fall through the LBR stack
  221. uint32_t LBRIndex = 0;
  222. // Reference to PerfSample.LBRStack
  223. const SmallVector<LBREntry, 16> &LBRStack;
  224. // Used to iterate the address range
  225. InstructionPointer InstPtr;
  226. UnwindState(const PerfSample *Sample, const ProfiledBinary *Binary)
  227. : Binary(Binary), LBRStack(Sample->LBRStack),
  228. InstPtr(Binary, Sample->CallStack.front()) {
  229. initFrameTrie(Sample->CallStack);
  230. }
  231. bool validateInitialState() {
  232. uint64_t LBRLeaf = LBRStack[LBRIndex].Target;
  233. uint64_t LeafAddr = CurrentLeafFrame->Address;
  234. assert((LBRLeaf != ExternalAddr || LBRLeaf == LeafAddr) &&
  235. "External leading LBR should match the leaf frame.");
  236. // When we take a stack sample, ideally the sampling distance between the
  237. // leaf IP of stack and the last LBR target shouldn't be very large.
  238. // Use a heuristic size (0x100) to filter out broken records.
  239. if (LeafAddr < LBRLeaf || LeafAddr >= LBRLeaf + 0x100) {
  240. WithColor::warning() << "Bogus trace: stack tip = "
  241. << format("%#010x", LeafAddr)
  242. << ", LBR tip = " << format("%#010x\n", LBRLeaf);
  243. return false;
  244. }
  245. return true;
  246. }
  247. void checkStateConsistency() {
  248. assert(InstPtr.Address == CurrentLeafFrame->Address &&
  249. "IP should align with context leaf");
  250. }
  251. bool hasNextLBR() const { return LBRIndex < LBRStack.size(); }
  252. uint64_t getCurrentLBRSource() const { return LBRStack[LBRIndex].Source; }
  253. uint64_t getCurrentLBRTarget() const { return LBRStack[LBRIndex].Target; }
  254. const LBREntry &getCurrentLBR() const { return LBRStack[LBRIndex]; }
  255. bool IsLastLBR() const { return LBRIndex == 0; }
  256. bool getLBRStackSize() const { return LBRStack.size(); }
  257. void advanceLBR() { LBRIndex++; }
  258. ProfiledFrame *getParentFrame() { return CurrentLeafFrame->Parent; }
  259. void pushFrame(uint64_t Address) {
  260. CurrentLeafFrame = CurrentLeafFrame->getOrCreateChildFrame(Address);
  261. }
  262. void switchToFrame(uint64_t Address) {
  263. if (CurrentLeafFrame->Address == Address)
  264. return;
  265. CurrentLeafFrame = CurrentLeafFrame->Parent->getOrCreateChildFrame(Address);
  266. }
  267. void popFrame() { CurrentLeafFrame = CurrentLeafFrame->Parent; }
  268. void clearCallStack() { CurrentLeafFrame = &DummyTrieRoot; }
  269. void initFrameTrie(const SmallVectorImpl<uint64_t> &CallStack) {
  270. ProfiledFrame *Cur = &DummyTrieRoot;
  271. for (auto Address : reverse(CallStack)) {
  272. Cur = Cur->getOrCreateChildFrame(Address);
  273. }
  274. CurrentLeafFrame = Cur;
  275. }
  276. ProfiledFrame *getDummyRootPtr() { return &DummyTrieRoot; }
  277. };
  278. // Base class for sample counter key with context
  279. struct ContextKey {
  280. uint64_t HashCode = 0;
  281. virtual ~ContextKey() = default;
  282. uint64_t getHashCode() {
  283. if (HashCode == 0)
  284. genHashCode();
  285. return HashCode;
  286. }
  287. virtual void genHashCode() = 0;
  288. virtual bool isEqual(const ContextKey *K) const {
  289. return HashCode == K->HashCode;
  290. };
  291. // Utilities for LLVM-style RTTI
  292. enum ContextKind { CK_StringBased, CK_ProbeBased };
  293. const ContextKind Kind;
  294. ContextKind getKind() const { return Kind; }
  295. ContextKey(ContextKind K) : Kind(K){};
  296. };
  297. // String based context id
  298. struct StringBasedCtxKey : public ContextKey {
  299. SampleContextFrameVector Context;
  300. bool WasLeafInlined;
  301. StringBasedCtxKey() : ContextKey(CK_StringBased), WasLeafInlined(false){};
  302. static bool classof(const ContextKey *K) {
  303. return K->getKind() == CK_StringBased;
  304. }
  305. bool isEqual(const ContextKey *K) const override {
  306. const StringBasedCtxKey *Other = dyn_cast<StringBasedCtxKey>(K);
  307. return Context == Other->Context;
  308. }
  309. void genHashCode() override {
  310. HashCode = hash_value(SampleContextFrames(Context));
  311. }
  312. };
  313. // Probe based context key as the intermediate key of context
  314. // String based context key will introduce redundant string handling
  315. // since the callee context is inferred from the context string which
  316. // need to be splitted by '@' to get the last location frame, so we
  317. // can just use probe instead and generate the string in the end.
  318. struct ProbeBasedCtxKey : public ContextKey {
  319. SmallVector<const MCDecodedPseudoProbe *, 16> Probes;
  320. ProbeBasedCtxKey() : ContextKey(CK_ProbeBased) {}
  321. static bool classof(const ContextKey *K) {
  322. return K->getKind() == CK_ProbeBased;
  323. }
  324. bool isEqual(const ContextKey *K) const override {
  325. const ProbeBasedCtxKey *O = dyn_cast<ProbeBasedCtxKey>(K);
  326. assert(O != nullptr && "Probe based key shouldn't be null in isEqual");
  327. return std::equal(Probes.begin(), Probes.end(), O->Probes.begin(),
  328. O->Probes.end());
  329. }
  330. void genHashCode() override {
  331. for (const auto *P : Probes) {
  332. HashCode = hash_combine(HashCode, P);
  333. }
  334. if (HashCode == 0) {
  335. // Avoid zero value of HashCode when it's an empty list
  336. HashCode = 1;
  337. }
  338. }
  339. };
  340. // The counter of branch samples for one function indexed by the branch,
  341. // which is represented as the source and target offset pair.
  342. using BranchSample = std::map<std::pair<uint64_t, uint64_t>, uint64_t>;
  343. // The counter of range samples for one function indexed by the range,
  344. // which is represented as the start and end offset pair.
  345. using RangeSample = std::map<std::pair<uint64_t, uint64_t>, uint64_t>;
  346. // Wrapper for sample counters including range counter and branch counter
  347. struct SampleCounter {
  348. RangeSample RangeCounter;
  349. BranchSample BranchCounter;
  350. void recordRangeCount(uint64_t Start, uint64_t End, uint64_t Repeat) {
  351. assert(Start <= End && "Invalid instruction range");
  352. RangeCounter[{Start, End}] += Repeat;
  353. }
  354. void recordBranchCount(uint64_t Source, uint64_t Target, uint64_t Repeat) {
  355. BranchCounter[{Source, Target}] += Repeat;
  356. }
  357. };
  358. // Sample counter with context to support context-sensitive profile
  359. using ContextSampleCounterMap =
  360. std::unordered_map<Hashable<ContextKey>, SampleCounter,
  361. Hashable<ContextKey>::Hash, Hashable<ContextKey>::Equal>;
  362. struct FrameStack {
  363. SmallVector<uint64_t, 16> Stack;
  364. ProfiledBinary *Binary;
  365. FrameStack(ProfiledBinary *B) : Binary(B) {}
  366. bool pushFrame(UnwindState::ProfiledFrame *Cur) {
  367. assert(!Cur->isExternalFrame() &&
  368. "External frame's not expected for context stack.");
  369. Stack.push_back(Cur->Address);
  370. return true;
  371. }
  372. void popFrame() {
  373. if (!Stack.empty())
  374. Stack.pop_back();
  375. }
  376. std::shared_ptr<StringBasedCtxKey> getContextKey();
  377. };
  378. struct ProbeStack {
  379. SmallVector<const MCDecodedPseudoProbe *, 16> Stack;
  380. ProfiledBinary *Binary;
  381. ProbeStack(ProfiledBinary *B) : Binary(B) {}
  382. bool pushFrame(UnwindState::ProfiledFrame *Cur) {
  383. assert(!Cur->isExternalFrame() &&
  384. "External frame's not expected for context stack.");
  385. const MCDecodedPseudoProbe *CallProbe =
  386. Binary->getCallProbeForAddr(Cur->Address);
  387. // We may not find a probe for a merged or external callsite.
  388. // Callsite merging may cause the loss of original probe IDs.
  389. // Cutting off the context from here since the inliner will
  390. // not know how to consume a context with unknown callsites.
  391. if (!CallProbe)
  392. return false;
  393. Stack.push_back(CallProbe);
  394. return true;
  395. }
  396. void popFrame() {
  397. if (!Stack.empty())
  398. Stack.pop_back();
  399. }
  400. // Use pseudo probe based context key to get the sample counter
  401. // A context stands for a call path from 'main' to an uninlined
  402. // callee with all inline frames recovered on that path. The probes
  403. // belonging to that call path is the probes either originated from
  404. // the callee or from any functions inlined into the callee. Since
  405. // pseudo probes are organized in a tri-tree style after decoded,
  406. // the tree path from the tri-tree root (which is the uninlined
  407. // callee) to the probe node forms an inline context.
  408. // Here we use a list of probe(pointer) as the context key to speed up
  409. // aggregation and the final context string will be generate in
  410. // ProfileGenerator
  411. std::shared_ptr<ProbeBasedCtxKey> getContextKey();
  412. };
  413. /*
  414. As in hybrid sample we have a group of LBRs and the most recent sampling call
  415. stack, we can walk through those LBRs to infer more call stacks which would be
  416. used as context for profile. VirtualUnwinder is the class to do the call stack
  417. unwinding based on LBR state. Two types of unwinding are processd here:
  418. 1) LBR unwinding and 2) linear range unwinding.
  419. Specifically, for each LBR entry(can be classified into call, return, regular
  420. branch), LBR unwinding will replay the operation by pushing, popping or
  421. switching leaf frame towards the call stack and since the initial call stack
  422. is most recently sampled, the replay should be in anti-execution order, i.e. for
  423. the regular case, pop the call stack when LBR is call, push frame on call stack
  424. when LBR is return. After each LBR processed, it also needs to align with the
  425. next LBR by going through instructions from previous LBR's target to current
  426. LBR's source, which is the linear unwinding. As instruction from linear range
  427. can come from different function by inlining, linear unwinding will do the range
  428. splitting and record counters by the range with same inline context. Over those
  429. unwinding process we will record each call stack as context id and LBR/linear
  430. range as sample counter for further CS profile generation.
  431. */
  432. class VirtualUnwinder {
  433. public:
  434. VirtualUnwinder(ContextSampleCounterMap *Counter, ProfiledBinary *B)
  435. : CtxCounterMap(Counter), Binary(B) {}
  436. bool unwind(const PerfSample *Sample, uint64_t Repeat);
  437. std::set<uint64_t> &getUntrackedCallsites() { return UntrackedCallsites; }
  438. uint64_t NumTotalBranches = 0;
  439. uint64_t NumExtCallBranch = 0;
  440. uint64_t NumMissingExternalFrame = 0;
  441. uint64_t NumMismatchedProEpiBranch = 0;
  442. uint64_t NumMismatchedExtCallBranch = 0;
  443. private:
  444. bool isCallState(UnwindState &State) const {
  445. // The tail call frame is always missing here in stack sample, we will
  446. // use a specific tail call tracker to infer it.
  447. return Binary->addressIsCall(State.getCurrentLBRSource());
  448. }
  449. bool isReturnState(UnwindState &State) const {
  450. // Simply check addressIsReturn, as ret is always reliable, both for
  451. // regular call and tail call.
  452. if (!Binary->addressIsReturn(State.getCurrentLBRSource()))
  453. return false;
  454. // In a callback case, a return from internal code, say A, to external
  455. // runtime can happen. The external runtime can then call back to
  456. // another internal routine, say B. Making an artificial branch that
  457. // looks like a return from A to B can confuse the unwinder to treat
  458. // the instruction before B as the call instruction. Here we detect this
  459. // case if the return target is not the next inst of call inst, then we just
  460. // do not treat it as a return.
  461. uint64_t CallAddr =
  462. Binary->getCallAddrFromFrameAddr(State.getCurrentLBRTarget());
  463. return (CallAddr != 0);
  464. }
  465. void unwindCall(UnwindState &State);
  466. void unwindLinear(UnwindState &State, uint64_t Repeat);
  467. void unwindReturn(UnwindState &State);
  468. void unwindBranch(UnwindState &State);
  469. template <typename T>
  470. void collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur, T &Stack);
  471. // Collect each samples on trie node by DFS traversal
  472. template <typename T>
  473. void collectSamplesFromFrameTrie(UnwindState::ProfiledFrame *Cur, T &Stack);
  474. void collectSamplesFromFrameTrie(UnwindState::ProfiledFrame *Cur);
  475. void recordRangeCount(uint64_t Start, uint64_t End, UnwindState &State,
  476. uint64_t Repeat);
  477. void recordBranchCount(const LBREntry &Branch, UnwindState &State,
  478. uint64_t Repeat);
  479. ContextSampleCounterMap *CtxCounterMap;
  480. // Profiled binary that current frame address belongs to
  481. ProfiledBinary *Binary;
  482. // Keep track of all untracked callsites
  483. std::set<uint64_t> UntrackedCallsites;
  484. };
  485. // Read perf trace to parse the events and samples.
  486. class PerfReaderBase {
  487. public:
  488. PerfReaderBase(ProfiledBinary *B, StringRef PerfTrace)
  489. : Binary(B), PerfTraceFile(PerfTrace) {
  490. // Initialize the base address to preferred address.
  491. Binary->setBaseAddress(Binary->getPreferredBaseAddress());
  492. };
  493. virtual ~PerfReaderBase() = default;
  494. static std::unique_ptr<PerfReaderBase> create(ProfiledBinary *Binary,
  495. PerfInputFile &PerfInput);
  496. // Entry of the reader to parse multiple perf traces
  497. virtual void parsePerfTraces() = 0;
  498. const ContextSampleCounterMap &getSampleCounters() const {
  499. return SampleCounters;
  500. }
  501. bool profileIsCSFlat() { return ProfileIsCSFlat; }
  502. protected:
  503. ProfiledBinary *Binary = nullptr;
  504. StringRef PerfTraceFile;
  505. ContextSampleCounterMap SampleCounters;
  506. bool ProfileIsCSFlat = false;
  507. uint64_t NumTotalSample = 0;
  508. uint64_t NumLeafExternalFrame = 0;
  509. uint64_t NumLeadingOutgoingLBR = 0;
  510. };
  511. // Read perf script to parse the events and samples.
  512. class PerfScriptReader : public PerfReaderBase {
  513. public:
  514. PerfScriptReader(ProfiledBinary *B, StringRef PerfTrace)
  515. : PerfReaderBase(B, PerfTrace){};
  516. // Entry of the reader to parse multiple perf traces
  517. virtual void parsePerfTraces() override;
  518. // Generate perf script from perf data
  519. static PerfInputFile convertPerfDataToTrace(ProfiledBinary *Binary,
  520. PerfInputFile &File);
  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. };
  578. /*
  579. The reader of LBR only perf script.
  580. A typical LBR sample is like:
  581. 40062f 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  582. ... 0x4005c8/0x4005dc/P/-/-/0
  583. */
  584. class LBRPerfReader : public PerfScriptReader {
  585. public:
  586. LBRPerfReader(ProfiledBinary *Binary, StringRef PerfTrace)
  587. : PerfScriptReader(Binary, PerfTrace){};
  588. // Parse the LBR only sample.
  589. virtual void parseSample(TraceStream &TraceIt, uint64_t Count) override;
  590. };
  591. /*
  592. Hybrid perf script includes a group of hybrid samples(LBRs + call stack),
  593. which is used to generate CS profile. An example of hybrid sample:
  594. 4005dc # call stack leaf
  595. 400634
  596. 400684 # call stack root
  597. 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
  598. ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
  599. */
  600. class HybridPerfReader : public PerfScriptReader {
  601. public:
  602. HybridPerfReader(ProfiledBinary *Binary, StringRef PerfTrace)
  603. : PerfScriptReader(Binary, PerfTrace){};
  604. // Parse the hybrid sample including the call and LBR line
  605. void parseSample(TraceStream &TraceIt, uint64_t Count) override;
  606. void generateUnsymbolizedProfile() override;
  607. private:
  608. // Unwind the hybrid samples after aggregration
  609. void unwindSamples();
  610. };
  611. /*
  612. Format of unsymbolized profile:
  613. [frame1 @ frame2 @ ...] # If it's a CS profile
  614. number of entries in RangeCounter
  615. from_1-to_1:count_1
  616. from_2-to_2:count_2
  617. ......
  618. from_n-to_n:count_n
  619. number of entries in BranchCounter
  620. src_1->dst_1:count_1
  621. src_2->dst_2:count_2
  622. ......
  623. src_n->dst_n:count_n
  624. [frame1 @ frame2 @ ...] # Next context
  625. ......
  626. Note that non-CS profile doesn't have the empty `[]` context.
  627. */
  628. class UnsymbolizedProfileReader : public PerfReaderBase {
  629. public:
  630. UnsymbolizedProfileReader(ProfiledBinary *Binary, StringRef PerfTrace)
  631. : PerfReaderBase(Binary, PerfTrace){};
  632. void parsePerfTraces() override;
  633. private:
  634. void readSampleCounters(TraceStream &TraceIt, SampleCounter &SCounters);
  635. void readUnsymbolizedProfile(StringRef Filename);
  636. std::unordered_set<std::string> ContextStrSet;
  637. };
  638. } // end namespace sampleprof
  639. } // end namespace llvm
  640. #endif