xray-account.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. //===- xray-account.h - XRay Function Call Accounting ---------------------===//
  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. //
  9. // This file implements basic function call accounting from an XRay trace.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include <algorithm>
  13. #include <cassert>
  14. #include <numeric>
  15. #include <system_error>
  16. #include <utility>
  17. #include "xray-account.h"
  18. #include "xray-registry.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/Support/FormatVariadic.h"
  21. #include "llvm/XRay/InstrumentationMap.h"
  22. #include "llvm/XRay/Trace.h"
  23. using namespace llvm;
  24. using namespace llvm::xray;
  25. static cl::SubCommand Account("account", "Function call accounting");
  26. static cl::opt<std::string> AccountInput(cl::Positional,
  27. cl::desc("<xray log file>"),
  28. cl::Required, cl::sub(Account));
  29. static cl::opt<bool>
  30. AccountKeepGoing("keep-going", cl::desc("Keep going on errors encountered"),
  31. cl::sub(Account), cl::init(false));
  32. static cl::alias AccountKeepGoing2("k", cl::aliasopt(AccountKeepGoing),
  33. cl::desc("Alias for -keep_going"));
  34. static cl::opt<bool> AccountRecursiveCallsOnly(
  35. "recursive-calls-only", cl::desc("Only count the calls that are recursive"),
  36. cl::sub(Account), cl::init(false));
  37. static cl::opt<bool> AccountDeduceSiblingCalls(
  38. "deduce-sibling-calls",
  39. cl::desc("Deduce sibling calls when unrolling function call stacks"),
  40. cl::sub(Account), cl::init(false));
  41. static cl::alias
  42. AccountDeduceSiblingCalls2("d", cl::aliasopt(AccountDeduceSiblingCalls),
  43. cl::desc("Alias for -deduce_sibling_calls"));
  44. static cl::opt<std::string>
  45. AccountOutput("output", cl::value_desc("output file"), cl::init("-"),
  46. cl::desc("output file; use '-' for stdout"),
  47. cl::sub(Account));
  48. static cl::alias AccountOutput2("o", cl::aliasopt(AccountOutput),
  49. cl::desc("Alias for -output"));
  50. enum class AccountOutputFormats { TEXT, CSV };
  51. static cl::opt<AccountOutputFormats>
  52. AccountOutputFormat("format", cl::desc("output format"),
  53. cl::values(clEnumValN(AccountOutputFormats::TEXT,
  54. "text", "report stats in text"),
  55. clEnumValN(AccountOutputFormats::CSV, "csv",
  56. "report stats in csv")),
  57. cl::sub(Account));
  58. static cl::alias AccountOutputFormat2("f", cl::desc("Alias of -format"),
  59. cl::aliasopt(AccountOutputFormat));
  60. enum class SortField {
  61. FUNCID,
  62. COUNT,
  63. MIN,
  64. MED,
  65. PCT90,
  66. PCT99,
  67. MAX,
  68. SUM,
  69. FUNC,
  70. };
  71. static cl::opt<SortField> AccountSortOutput(
  72. "sort", cl::desc("sort output by this field"), cl::value_desc("field"),
  73. cl::sub(Account), cl::init(SortField::FUNCID),
  74. cl::values(clEnumValN(SortField::FUNCID, "funcid", "function id"),
  75. clEnumValN(SortField::COUNT, "count", "funciton call counts"),
  76. clEnumValN(SortField::MIN, "min", "minimum function durations"),
  77. clEnumValN(SortField::MED, "med", "median function durations"),
  78. clEnumValN(SortField::PCT90, "90p", "90th percentile durations"),
  79. clEnumValN(SortField::PCT99, "99p", "99th percentile durations"),
  80. clEnumValN(SortField::MAX, "max", "maximum function durations"),
  81. clEnumValN(SortField::SUM, "sum", "sum of call durations"),
  82. clEnumValN(SortField::FUNC, "func", "function names")));
  83. static cl::alias AccountSortOutput2("s", cl::aliasopt(AccountSortOutput),
  84. cl::desc("Alias for -sort"));
  85. enum class SortDirection {
  86. ASCENDING,
  87. DESCENDING,
  88. };
  89. static cl::opt<SortDirection> AccountSortOrder(
  90. "sortorder", cl::desc("sort ordering"), cl::init(SortDirection::ASCENDING),
  91. cl::values(clEnumValN(SortDirection::ASCENDING, "asc", "ascending"),
  92. clEnumValN(SortDirection::DESCENDING, "dsc", "descending")),
  93. cl::sub(Account));
  94. static cl::alias AccountSortOrder2("r", cl::aliasopt(AccountSortOrder),
  95. cl::desc("Alias for -sortorder"));
  96. static cl::opt<int> AccountTop("top", cl::desc("only show the top N results"),
  97. cl::value_desc("N"), cl::sub(Account),
  98. cl::init(-1));
  99. static cl::alias AccountTop2("p", cl::desc("Alias for -top"),
  100. cl::aliasopt(AccountTop));
  101. static cl::opt<std::string>
  102. AccountInstrMap("instr_map",
  103. cl::desc("binary with the instrumentation map, or "
  104. "a separate instrumentation map"),
  105. cl::value_desc("binary with xray_instr_map"),
  106. cl::sub(Account), cl::init(""));
  107. static cl::alias AccountInstrMap2("m", cl::aliasopt(AccountInstrMap),
  108. cl::desc("Alias for -instr_map"));
  109. namespace {
  110. template <class T, class U> void setMinMax(std::pair<T, T> &MM, U &&V) {
  111. if (MM.first == 0 || MM.second == 0)
  112. MM = std::make_pair(std::forward<U>(V), std::forward<U>(V));
  113. else
  114. MM = std::make_pair(std::min(MM.first, V), std::max(MM.second, V));
  115. }
  116. template <class T> T diff(T L, T R) { return std::max(L, R) - std::min(L, R); }
  117. } // namespace
  118. using RecursionStatus = LatencyAccountant::FunctionStack::RecursionStatus;
  119. RecursionStatus &RecursionStatus::operator++() {
  120. auto Depth = Bitfield::get<RecursionStatus::Depth>(Storage);
  121. assert(Depth >= 0 && Depth < std::numeric_limits<decltype(Depth)>::max());
  122. ++Depth;
  123. Bitfield::set<RecursionStatus::Depth>(Storage, Depth); // ++Storage
  124. // Did this function just (maybe indirectly) call itself the first time?
  125. if (!isRecursive() && Depth == 2) // Storage == 2 / Storage s> 1
  126. Bitfield::set<RecursionStatus::IsRecursive>(Storage,
  127. true); // Storage |= INT_MIN
  128. return *this;
  129. }
  130. RecursionStatus &RecursionStatus::operator--() {
  131. auto Depth = Bitfield::get<RecursionStatus::Depth>(Storage);
  132. assert(Depth > 0);
  133. --Depth;
  134. Bitfield::set<RecursionStatus::Depth>(Storage, Depth); // --Storage
  135. // Did we leave a function that previouly (maybe indirectly) called itself?
  136. if (isRecursive() && Depth == 0) // Storage == INT_MIN
  137. Bitfield::set<RecursionStatus::IsRecursive>(Storage, false); // Storage = 0
  138. return *this;
  139. }
  140. bool RecursionStatus::isRecursive() const {
  141. return Bitfield::get<RecursionStatus::IsRecursive>(Storage); // Storage s< 0
  142. }
  143. bool LatencyAccountant::accountRecord(const XRayRecord &Record) {
  144. setMinMax(PerThreadMinMaxTSC[Record.TId], Record.TSC);
  145. setMinMax(PerCPUMinMaxTSC[Record.CPU], Record.TSC);
  146. if (CurrentMaxTSC == 0)
  147. CurrentMaxTSC = Record.TSC;
  148. if (Record.TSC < CurrentMaxTSC)
  149. return false;
  150. auto &ThreadStack = PerThreadFunctionStack[Record.TId];
  151. if (RecursiveCallsOnly && !ThreadStack.RecursionDepth)
  152. ThreadStack.RecursionDepth.emplace();
  153. switch (Record.Type) {
  154. case RecordTypes::CUSTOM_EVENT:
  155. case RecordTypes::TYPED_EVENT:
  156. // TODO: Support custom and typed event accounting in the future.
  157. return true;
  158. case RecordTypes::ENTER:
  159. case RecordTypes::ENTER_ARG: {
  160. ThreadStack.Stack.emplace_back(Record.FuncId, Record.TSC);
  161. if (ThreadStack.RecursionDepth)
  162. ++(*ThreadStack.RecursionDepth)[Record.FuncId];
  163. break;
  164. }
  165. case RecordTypes::EXIT:
  166. case RecordTypes::TAIL_EXIT: {
  167. if (ThreadStack.Stack.empty())
  168. return false;
  169. if (ThreadStack.Stack.back().first == Record.FuncId) {
  170. const auto &Top = ThreadStack.Stack.back();
  171. if (!ThreadStack.RecursionDepth ||
  172. (*ThreadStack.RecursionDepth)[Top.first].isRecursive())
  173. recordLatency(Top.first, diff(Top.second, Record.TSC));
  174. if (ThreadStack.RecursionDepth)
  175. --(*ThreadStack.RecursionDepth)[Top.first];
  176. ThreadStack.Stack.pop_back();
  177. break;
  178. }
  179. if (!DeduceSiblingCalls)
  180. return false;
  181. // Look for the parent up the stack.
  182. auto Parent =
  183. std::find_if(ThreadStack.Stack.rbegin(), ThreadStack.Stack.rend(),
  184. [&](const std::pair<const int32_t, uint64_t> &E) {
  185. return E.first == Record.FuncId;
  186. });
  187. if (Parent == ThreadStack.Stack.rend())
  188. return false;
  189. // Account time for this apparently sibling call exit up the stack.
  190. // Considering the following case:
  191. //
  192. // f()
  193. // g()
  194. // h()
  195. //
  196. // We might only ever see the following entries:
  197. //
  198. // -> f()
  199. // -> g()
  200. // -> h()
  201. // <- h()
  202. // <- f()
  203. //
  204. // Now we don't see the exit to g() because some older version of the XRay
  205. // runtime wasn't instrumenting tail exits. If we don't deduce tail calls,
  206. // we may potentially never account time for g() -- and this code would have
  207. // already bailed out, because `<- f()` doesn't match the current "top" of
  208. // stack where we're waiting for the exit to `g()` instead. This is not
  209. // ideal and brittle -- so instead we provide a potentially inaccurate
  210. // accounting of g() instead, computing it from the exit of f().
  211. //
  212. // While it might be better that we account the time between `-> g()` and
  213. // `-> h()` as the proper accounting of time for g() here, this introduces
  214. // complexity to do correctly (need to backtrack, etc.).
  215. //
  216. // FIXME: Potentially implement the more complex deduction algorithm?
  217. auto R = make_range(std::next(Parent).base(), ThreadStack.Stack.end());
  218. for (auto &E : R) {
  219. if (!ThreadStack.RecursionDepth ||
  220. (*ThreadStack.RecursionDepth)[E.first].isRecursive())
  221. recordLatency(E.first, diff(E.second, Record.TSC));
  222. }
  223. for (auto &Top : reverse(R)) {
  224. if (ThreadStack.RecursionDepth)
  225. --(*ThreadStack.RecursionDepth)[Top.first];
  226. ThreadStack.Stack.pop_back();
  227. }
  228. break;
  229. }
  230. }
  231. return true;
  232. }
  233. namespace {
  234. // We consolidate the data into a struct which we can output in various forms.
  235. struct ResultRow {
  236. uint64_t Count;
  237. double Min;
  238. double Median;
  239. double Pct90;
  240. double Pct99;
  241. double Max;
  242. double Sum;
  243. std::string DebugInfo;
  244. std::string Function;
  245. };
  246. ResultRow getStats(MutableArrayRef<uint64_t> Timings) {
  247. assert(!Timings.empty());
  248. ResultRow R;
  249. R.Sum = std::accumulate(Timings.begin(), Timings.end(), 0.0);
  250. auto MinMax = std::minmax_element(Timings.begin(), Timings.end());
  251. R.Min = *MinMax.first;
  252. R.Max = *MinMax.second;
  253. R.Count = Timings.size();
  254. auto MedianOff = Timings.size() / 2;
  255. std::nth_element(Timings.begin(), Timings.begin() + MedianOff, Timings.end());
  256. R.Median = Timings[MedianOff];
  257. size_t Pct90Off = std::floor(Timings.size() * 0.9);
  258. std::nth_element(Timings.begin(), Timings.begin() + (uint64_t)Pct90Off,
  259. Timings.end());
  260. R.Pct90 = Timings[Pct90Off];
  261. size_t Pct99Off = std::floor(Timings.size() * 0.99);
  262. std::nth_element(Timings.begin(), Timings.begin() + (uint64_t)Pct99Off,
  263. Timings.end());
  264. R.Pct99 = Timings[Pct99Off];
  265. return R;
  266. }
  267. } // namespace
  268. using TupleType = std::tuple<int32_t, uint64_t, ResultRow>;
  269. template <typename F>
  270. static void sortByKey(std::vector<TupleType> &Results, F Fn) {
  271. bool ASC = AccountSortOrder == SortDirection::ASCENDING;
  272. llvm::sort(Results, [=](const TupleType &L, const TupleType &R) {
  273. return ASC ? Fn(L) < Fn(R) : Fn(L) > Fn(R);
  274. });
  275. }
  276. template <class F>
  277. void LatencyAccountant::exportStats(const XRayFileHeader &Header, F Fn) const {
  278. std::vector<TupleType> Results;
  279. Results.reserve(FunctionLatencies.size());
  280. for (auto FT : FunctionLatencies) {
  281. const auto &FuncId = FT.first;
  282. auto &Timings = FT.second;
  283. Results.emplace_back(FuncId, Timings.size(), getStats(Timings));
  284. auto &Row = std::get<2>(Results.back());
  285. if (Header.CycleFrequency) {
  286. double CycleFrequency = Header.CycleFrequency;
  287. Row.Min /= CycleFrequency;
  288. Row.Median /= CycleFrequency;
  289. Row.Pct90 /= CycleFrequency;
  290. Row.Pct99 /= CycleFrequency;
  291. Row.Max /= CycleFrequency;
  292. Row.Sum /= CycleFrequency;
  293. }
  294. Row.Function = FuncIdHelper.SymbolOrNumber(FuncId);
  295. Row.DebugInfo = FuncIdHelper.FileLineAndColumn(FuncId);
  296. }
  297. // Sort the data according to user-provided flags.
  298. switch (AccountSortOutput) {
  299. case SortField::FUNCID:
  300. sortByKey(Results, [](const TupleType &X) { return std::get<0>(X); });
  301. break;
  302. case SortField::COUNT:
  303. sortByKey(Results, [](const TupleType &X) { return std::get<1>(X); });
  304. break;
  305. case SortField::MIN:
  306. sortByKey(Results, [](const TupleType &X) { return std::get<2>(X).Min; });
  307. break;
  308. case SortField::MED:
  309. sortByKey(Results, [](const TupleType &X) { return std::get<2>(X).Median; });
  310. break;
  311. case SortField::PCT90:
  312. sortByKey(Results, [](const TupleType &X) { return std::get<2>(X).Pct90; });
  313. break;
  314. case SortField::PCT99:
  315. sortByKey(Results, [](const TupleType &X) { return std::get<2>(X).Pct99; });
  316. break;
  317. case SortField::MAX:
  318. sortByKey(Results, [](const TupleType &X) { return std::get<2>(X).Max; });
  319. break;
  320. case SortField::SUM:
  321. sortByKey(Results, [](const TupleType &X) { return std::get<2>(X).Sum; });
  322. break;
  323. case SortField::FUNC:
  324. llvm_unreachable("Not implemented");
  325. }
  326. if (AccountTop > 0) {
  327. auto MaxTop =
  328. std::min(AccountTop.getValue(), static_cast<int>(Results.size()));
  329. Results.erase(Results.begin() + MaxTop, Results.end());
  330. }
  331. for (const auto &R : Results)
  332. Fn(std::get<0>(R), std::get<1>(R), std::get<2>(R));
  333. }
  334. void LatencyAccountant::exportStatsAsText(raw_ostream &OS,
  335. const XRayFileHeader &Header) const {
  336. OS << "Functions with latencies: " << FunctionLatencies.size() << "\n";
  337. // We spend some effort to make the text output more readable, so we do the
  338. // following formatting decisions for each of the fields:
  339. //
  340. // - funcid: 32-bit, but we can determine the largest number and be
  341. // between
  342. // a minimum of 5 characters, up to 9 characters, right aligned.
  343. // - count: 64-bit, but we can determine the largest number and be
  344. // between
  345. // a minimum of 5 characters, up to 9 characters, right aligned.
  346. // - min, median, 90pct, 99pct, max: double precision, but we want to keep
  347. // the values in seconds, with microsecond precision (0.000'001), so we
  348. // have at most 6 significant digits, with the whole number part to be
  349. // at
  350. // least 1 character. For readability we'll right-align, with full 9
  351. // characters each.
  352. // - debug info, function name: we format this as a concatenation of the
  353. // debug info and the function name.
  354. //
  355. static constexpr char StatsHeaderFormat[] =
  356. "{0,+9} {1,+10} [{2,+9}, {3,+9}, {4,+9}, {5,+9}, {6,+9}] {7,+9}";
  357. static constexpr char StatsFormat[] =
  358. R"({0,+9} {1,+10} [{2,+9:f6}, {3,+9:f6}, {4,+9:f6}, {5,+9:f6}, {6,+9:f6}] {7,+9:f6})";
  359. OS << llvm::formatv(StatsHeaderFormat, "funcid", "count", "min", "med", "90p",
  360. "99p", "max", "sum")
  361. << llvm::formatv(" {0,-12}\n", "function");
  362. exportStats(Header, [&](int32_t FuncId, size_t Count, const ResultRow &Row) {
  363. OS << llvm::formatv(StatsFormat, FuncId, Count, Row.Min, Row.Median,
  364. Row.Pct90, Row.Pct99, Row.Max, Row.Sum)
  365. << " " << Row.DebugInfo << ": " << Row.Function << "\n";
  366. });
  367. }
  368. void LatencyAccountant::exportStatsAsCSV(raw_ostream &OS,
  369. const XRayFileHeader &Header) const {
  370. OS << "funcid,count,min,median,90%ile,99%ile,max,sum,debug,function\n";
  371. exportStats(Header, [&](int32_t FuncId, size_t Count, const ResultRow &Row) {
  372. OS << FuncId << ',' << Count << ',' << Row.Min << ',' << Row.Median << ','
  373. << Row.Pct90 << ',' << Row.Pct99 << ',' << Row.Max << "," << Row.Sum
  374. << ",\"" << Row.DebugInfo << "\",\"" << Row.Function << "\"\n";
  375. });
  376. }
  377. using namespace llvm::xray;
  378. namespace llvm {
  379. template <> struct format_provider<llvm::xray::RecordTypes> {
  380. static void format(const llvm::xray::RecordTypes &T, raw_ostream &Stream,
  381. StringRef Style) {
  382. switch (T) {
  383. case RecordTypes::ENTER:
  384. Stream << "enter";
  385. break;
  386. case RecordTypes::ENTER_ARG:
  387. Stream << "enter-arg";
  388. break;
  389. case RecordTypes::EXIT:
  390. Stream << "exit";
  391. break;
  392. case RecordTypes::TAIL_EXIT:
  393. Stream << "tail-exit";
  394. break;
  395. case RecordTypes::CUSTOM_EVENT:
  396. Stream << "custom-event";
  397. break;
  398. case RecordTypes::TYPED_EVENT:
  399. Stream << "typed-event";
  400. break;
  401. }
  402. }
  403. };
  404. } // namespace llvm
  405. static CommandRegistration Unused(&Account, []() -> Error {
  406. InstrumentationMap Map;
  407. if (!AccountInstrMap.empty()) {
  408. auto InstrumentationMapOrError = loadInstrumentationMap(AccountInstrMap);
  409. if (!InstrumentationMapOrError)
  410. return joinErrors(make_error<StringError>(
  411. Twine("Cannot open instrumentation map '") +
  412. AccountInstrMap + "'",
  413. std::make_error_code(std::errc::invalid_argument)),
  414. InstrumentationMapOrError.takeError());
  415. Map = std::move(*InstrumentationMapOrError);
  416. }
  417. std::error_code EC;
  418. raw_fd_ostream OS(AccountOutput, EC, sys::fs::OpenFlags::OF_TextWithCRLF);
  419. if (EC)
  420. return make_error<StringError>(
  421. Twine("Cannot open file '") + AccountOutput + "' for writing.", EC);
  422. const auto &FunctionAddresses = Map.getFunctionAddresses();
  423. symbolize::LLVMSymbolizer Symbolizer;
  424. llvm::xray::FuncIdConversionHelper FuncIdHelper(AccountInstrMap, Symbolizer,
  425. FunctionAddresses);
  426. xray::LatencyAccountant FCA(FuncIdHelper, AccountRecursiveCallsOnly,
  427. AccountDeduceSiblingCalls);
  428. auto TraceOrErr = loadTraceFile(AccountInput);
  429. if (!TraceOrErr)
  430. return joinErrors(
  431. make_error<StringError>(
  432. Twine("Failed loading input file '") + AccountInput + "'",
  433. std::make_error_code(std::errc::executable_format_error)),
  434. TraceOrErr.takeError());
  435. auto &T = *TraceOrErr;
  436. for (const auto &Record : T) {
  437. if (FCA.accountRecord(Record))
  438. continue;
  439. errs()
  440. << "Error processing record: "
  441. << llvm::formatv(
  442. R"({{type: {0}; cpu: {1}; record-type: {2}; function-id: {3}; tsc: {4}; thread-id: {5}; process-id: {6}}})",
  443. Record.RecordType, Record.CPU, Record.Type, Record.FuncId,
  444. Record.TSC, Record.TId, Record.PId)
  445. << '\n';
  446. for (const auto &ThreadStack : FCA.getPerThreadFunctionStack()) {
  447. errs() << "Thread ID: " << ThreadStack.first << "\n";
  448. if (ThreadStack.second.Stack.empty()) {
  449. errs() << " (empty stack)\n";
  450. continue;
  451. }
  452. auto Level = ThreadStack.second.Stack.size();
  453. for (const auto &Entry : llvm::reverse(ThreadStack.second.Stack))
  454. errs() << " #" << Level-- << "\t"
  455. << FuncIdHelper.SymbolOrNumber(Entry.first) << '\n';
  456. }
  457. if (!AccountKeepGoing)
  458. return make_error<StringError>(
  459. Twine("Failed accounting function calls in file '") + AccountInput +
  460. "'.",
  461. std::make_error_code(std::errc::executable_format_error));
  462. }
  463. switch (AccountOutputFormat) {
  464. case AccountOutputFormats::TEXT:
  465. FCA.exportStatsAsText(OS, T.getFileHeader());
  466. break;
  467. case AccountOutputFormats::CSV:
  468. FCA.exportStatsAsCSV(OS, T.getFileHeader());
  469. break;
  470. }
  471. return Error::success();
  472. });