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