1 //===- xray-converter.cpp: XRay Trace Conversion --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements the trace conversion functions.
12 //===----------------------------------------------------------------------===//
13 #include "xray-converter.h"
15 #include "trie-node.h"
16 #include "xray-registry.h"
17 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
18 #include "llvm/Support/EndianStream.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/FormatVariadic.h"
21 #include "llvm/Support/ScopedPrinter.h"
22 #include "llvm/Support/YAMLTraits.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/XRay/InstrumentationMap.h"
25 #include "llvm/XRay/Trace.h"
26 #include "llvm/XRay/YAMLXRayRecord.h"
32 // ----------------------------------------------------------------------------
33 static cl::SubCommand Convert("convert", "Trace Format Conversion");
34 static cl::opt<std::string> ConvertInput(cl::Positional,
35 cl::desc("<xray log file>"),
36 cl::Required, cl::sub(Convert));
37 enum class ConvertFormats { BINARY, YAML, CHROME_TRACE_EVENT };
38 static cl::opt<ConvertFormats> ConvertOutputFormat(
39 "output-format", cl::desc("output format"),
40 cl::values(clEnumValN(ConvertFormats::BINARY, "raw", "output in binary"),
41 clEnumValN(ConvertFormats::YAML, "yaml", "output in yaml"),
42 clEnumValN(ConvertFormats::CHROME_TRACE_EVENT, "trace_event",
43 "Output in chrome's trace event format. "
44 "May be visualized with the Catapult trace viewer.")),
46 static cl::alias ConvertOutputFormat2("f", cl::aliasopt(ConvertOutputFormat),
47 cl::desc("Alias for -output-format"),
49 static cl::opt<std::string>
50 ConvertOutput("output", cl::value_desc("output file"), cl::init("-"),
51 cl::desc("output file; use '-' for stdout"),
53 static cl::alias ConvertOutput2("o", cl::aliasopt(ConvertOutput),
54 cl::desc("Alias for -output"),
58 ConvertSymbolize("symbolize",
59 cl::desc("symbolize function ids from the input log"),
60 cl::init(false), cl::sub(Convert));
61 static cl::alias ConvertSymbolize2("y", cl::aliasopt(ConvertSymbolize),
62 cl::desc("Alias for -symbolize"),
65 static cl::opt<std::string>
66 ConvertInstrMap("instr_map",
67 cl::desc("binary with the instrumentation map, or "
68 "a separate instrumentation map"),
69 cl::value_desc("binary with xray_instr_map"),
70 cl::sub(Convert), cl::init(""));
71 static cl::alias ConvertInstrMap2("m", cl::aliasopt(ConvertInstrMap),
72 cl::desc("Alias for -instr_map"),
74 static cl::opt<bool> ConvertSortInput(
76 cl::desc("determines whether to sort input log records by timestamp"),
77 cl::sub(Convert), cl::init(true));
78 static cl::alias ConvertSortInput2("s", cl::aliasopt(ConvertSortInput),
79 cl::desc("Alias for -sort"),
82 using llvm::yaml::Output;
84 void TraceConverter::exportAsYAML(const Trace &Records, raw_ostream &OS) {
86 const auto &FH = Records.getFileHeader();
87 Trace.Header = {FH.Version, FH.Type, FH.ConstantTSC, FH.NonstopTSC,
89 Trace.Records.reserve(Records.size());
90 for (const auto &R : Records) {
91 Trace.Records.push_back({R.RecordType, R.CPU, R.Type, R.FuncId,
92 Symbolize ? FuncIdHelper.SymbolOrNumber(R.FuncId)
93 : llvm::to_string(R.FuncId),
94 R.TSC, R.TId, R.PId, R.CallArgs, R.Data});
96 Output Out(OS, nullptr, 0);
97 Out.setWriteDefaultValues(false);
101 void TraceConverter::exportAsRAWv1(const Trace &Records, raw_ostream &OS) {
102 // First write out the file header, in the correct endian-appropriate format
103 // (XRay assumes currently little endian).
104 support::endian::Writer Writer(OS, support::endianness::little);
105 const auto &FH = Records.getFileHeader();
106 Writer.write(FH.Version);
107 Writer.write(FH.Type);
108 uint32_t Bitfield{0};
112 Bitfield |= 1uL << 1;
113 Writer.write(Bitfield);
114 Writer.write(FH.CycleFrequency);
116 // There's 16 bytes of padding at the end of the file header.
117 static constexpr uint32_t Padding4B = 0;
118 Writer.write(Padding4B);
119 Writer.write(Padding4B);
120 Writer.write(Padding4B);
121 Writer.write(Padding4B);
123 // Then write out the rest of the records, still in an endian-appropriate
125 for (const auto &R : Records) {
127 case RecordTypes::ENTER:
128 case RecordTypes::ENTER_ARG:
129 Writer.write(R.RecordType);
130 Writer.write(static_cast<uint8_t>(R.CPU));
131 Writer.write(uint8_t{0});
133 case RecordTypes::EXIT:
134 Writer.write(R.RecordType);
135 Writer.write(static_cast<uint8_t>(R.CPU));
136 Writer.write(uint8_t{1});
138 case RecordTypes::TAIL_EXIT:
139 Writer.write(R.RecordType);
140 Writer.write(static_cast<uint8_t>(R.CPU));
141 Writer.write(uint8_t{2});
143 case RecordTypes::CUSTOM_EVENT:
144 case RecordTypes::TYPED_EVENT:
145 // Skip custom and typed event records for v1 logs.
148 Writer.write(R.FuncId);
155 Writer.write(Padding4B);
157 Writer.write(Padding4B);
158 Writer.write(Padding4B);
164 // A structure that allows building a dictionary of stack ids for the Chrome
165 // trace event format.
167 // Each Stack of function calls has a unique ID.
170 // Bookkeeping so that IDs can be maintained uniquely across threads.
171 // Traversal keeps sibling pointers to other threads stacks. This is helpful
172 // to determine when a thread encounters a new stack and should assign a new
174 SmallVector<TrieNode<StackIdData> *, 4> siblings;
177 using StackTrieNode = TrieNode<StackIdData>;
179 // A helper function to find the sibling nodes for an encountered function in a
180 // thread of execution. Relies on the invariant that each time a new node is
181 // traversed in a thread, sibling bidirectional pointers are maintained.
182 SmallVector<StackTrieNode *, 4>
183 findSiblings(StackTrieNode *parent, int32_t FnId, uint32_t TId,
184 const DenseMap<uint32_t, SmallVector<StackTrieNode *, 4>>
185 &StackRootsByThreadId) {
187 SmallVector<StackTrieNode *, 4> Siblings{};
189 if (parent == nullptr) {
190 for (auto map_iter : StackRootsByThreadId) {
191 // Only look for siblings in other threads.
192 if (map_iter.first != TId)
193 for (auto node_iter : map_iter.second) {
194 if (node_iter->FuncId == FnId)
195 Siblings.push_back(node_iter);
201 for (auto *ParentSibling : parent->ExtraData.siblings)
202 for (auto node_iter : ParentSibling->Callees)
203 if (node_iter->FuncId == FnId)
204 Siblings.push_back(node_iter);
209 // Given a function being invoked in a thread with id TId, finds and returns the
210 // StackTrie representing the function call stack. If no node exists, creates
211 // the node. Assigns unique IDs to stacks newly encountered among all threads
212 // and keeps sibling links up to when creating new nodes.
213 StackTrieNode *findOrCreateStackNode(
214 StackTrieNode *Parent, int32_t FuncId, uint32_t TId,
215 DenseMap<uint32_t, SmallVector<StackTrieNode *, 4>> &StackRootsByThreadId,
216 DenseMap<unsigned, StackTrieNode *> &StacksByStackId, unsigned *id_counter,
217 std::forward_list<StackTrieNode> &NodeStore) {
218 SmallVector<StackTrieNode *, 4> &ParentCallees =
219 Parent == nullptr ? StackRootsByThreadId[TId] : Parent->Callees;
220 auto match = find_if(ParentCallees, [FuncId](StackTrieNode *ParentCallee) {
221 return FuncId == ParentCallee->FuncId;
223 if (match != ParentCallees.end())
226 SmallVector<StackTrieNode *, 4> siblings =
227 findSiblings(Parent, FuncId, TId, StackRootsByThreadId);
228 if (siblings.empty()) {
229 NodeStore.push_front({FuncId, Parent, {}, {(*id_counter)++, {}}});
230 StackTrieNode *CurrentStack = &NodeStore.front();
231 StacksByStackId[*id_counter - 1] = CurrentStack;
232 ParentCallees.push_back(CurrentStack);
235 unsigned stack_id = siblings[0]->ExtraData.id;
236 NodeStore.push_front({FuncId, Parent, {}, {stack_id, std::move(siblings)}});
237 StackTrieNode *CurrentStack = &NodeStore.front();
238 for (auto *sibling : CurrentStack->ExtraData.siblings)
239 sibling->ExtraData.siblings.push_back(CurrentStack);
240 ParentCallees.push_back(CurrentStack);
244 void writeTraceViewerRecord(uint16_t Version, raw_ostream &OS, int32_t FuncId,
245 uint32_t TId, uint32_t PId, bool Symbolize,
246 const FuncIdConversionHelper &FuncIdHelper,
247 double EventTimestampUs,
248 const StackTrieNode &StackCursor,
249 StringRef FunctionPhenotype) {
253 R"({ "name" : "{0}", "ph" : "{1}", "tid" : "{2}", "pid" : "{3}", )"
254 R"("ts" : "{4:f4}", "sf" : "{5}" })",
255 (Symbolize ? FuncIdHelper.SymbolOrNumber(FuncId)
256 : llvm::to_string(FuncId)),
257 FunctionPhenotype, TId, PId, EventTimestampUs,
258 StackCursor.ExtraData.id);
261 R"({ "name" : "{0}", "ph" : "{1}", "tid" : "{2}", "pid" : "1", )"
262 R"("ts" : "{3:f3}", "sf" : "{4}" })",
263 (Symbolize ? FuncIdHelper.SymbolOrNumber(FuncId)
264 : llvm::to_string(FuncId)),
265 FunctionPhenotype, TId, EventTimestampUs, StackCursor.ExtraData.id);
271 void TraceConverter::exportAsChromeTraceEventFormat(const Trace &Records,
273 const auto &FH = Records.getFileHeader();
274 auto Version = FH.Version;
275 auto CycleFreq = FH.CycleFrequency;
277 unsigned id_counter = 0;
279 OS << "{\n \"traceEvents\": [";
280 DenseMap<uint32_t, StackTrieNode *> StackCursorByThreadId{};
281 DenseMap<uint32_t, SmallVector<StackTrieNode *, 4>> StackRootsByThreadId{};
282 DenseMap<unsigned, StackTrieNode *> StacksByStackId{};
283 std::forward_list<StackTrieNode> NodeStore{};
285 for (const auto &R : Records) {
286 if (loop_count++ == 0)
291 // Chrome trace event format always wants data in micros.
292 // CyclesPerMicro = CycleHertz / 10^6
293 // TSC / CyclesPerMicro == TSC * 10^6 / CycleHertz == MicroTimestamp
294 // Could lose some precision here by converting the TSC to a double to
295 // multiply by the period in micros. 52 bit mantissa is a good start though.
296 // TODO: Make feature request to Chrome Trace viewer to accept ticks and a
297 // frequency or do some more involved calculation to avoid dangers of
299 double EventTimestampUs = double(1000000) / CycleFreq * double(R.TSC);
300 StackTrieNode *&StackCursor = StackCursorByThreadId[R.TId];
302 case RecordTypes::CUSTOM_EVENT:
303 case RecordTypes::TYPED_EVENT:
304 // TODO: Support typed and custom event rendering on Chrome Trace Viewer.
306 case RecordTypes::ENTER:
307 case RecordTypes::ENTER_ARG:
308 StackCursor = findOrCreateStackNode(StackCursor, R.FuncId, R.TId,
309 StackRootsByThreadId, StacksByStackId,
310 &id_counter, NodeStore);
311 // Each record is represented as a json dictionary with function name,
312 // type of B for begin or E for end, thread id, process id,
313 // timestamp in microseconds, and a stack frame id. The ids are logged
314 // in an id dictionary after the events.
315 writeTraceViewerRecord(Version, OS, R.FuncId, R.TId, R.PId, Symbolize,
316 FuncIdHelper, EventTimestampUs, *StackCursor, "B");
318 case RecordTypes::EXIT:
319 case RecordTypes::TAIL_EXIT:
320 // No entries to record end for.
321 if (StackCursor == nullptr)
323 // Should we emit an END record anyway or account this condition?
324 // (And/Or in loop termination below)
325 StackTrieNode *PreviousCursor = nullptr;
327 if (PreviousCursor != nullptr) {
330 writeTraceViewerRecord(Version, OS, StackCursor->FuncId, R.TId, R.PId,
331 Symbolize, FuncIdHelper, EventTimestampUs,
333 PreviousCursor = StackCursor;
334 StackCursor = StackCursor->Parent;
335 } while (PreviousCursor->FuncId != R.FuncId && StackCursor != nullptr);
339 OS << "\n ],\n"; // Close the Trace Events array.
341 << "\"displayTimeUnit\": \"ns\",\n";
343 // The stackFrames dictionary substantially reduces size of the output file by
344 // avoiding repeating the entire call stack of function names for each entry.
345 OS << R"( "stackFrames": {)";
346 int stack_frame_count = 0;
347 for (auto map_iter : StacksByStackId) {
348 if (stack_frame_count++ == 0)
354 R"("{0}" : { "name" : "{1}")", map_iter.first,
355 (Symbolize ? FuncIdHelper.SymbolOrNumber(map_iter.second->FuncId)
356 : llvm::to_string(map_iter.second->FuncId)));
357 if (map_iter.second->Parent != nullptr)
358 OS << llvm::formatv(R"(, "parent": "{0}")",
359 map_iter.second->Parent->ExtraData.id);
362 OS << "\n }\n"; // Close the stack frames map.
363 OS << "}\n"; // Close the JSON entry.
369 static CommandRegistration Unused(&Convert, []() -> Error {
370 // FIXME: Support conversion to BINARY when upgrading XRay trace versions.
371 InstrumentationMap Map;
372 if (!ConvertInstrMap.empty()) {
373 auto InstrumentationMapOrError = loadInstrumentationMap(ConvertInstrMap);
374 if (!InstrumentationMapOrError)
375 return joinErrors(make_error<StringError>(
376 Twine("Cannot open instrumentation map '") +
377 ConvertInstrMap + "'",
378 std::make_error_code(std::errc::invalid_argument)),
379 InstrumentationMapOrError.takeError());
380 Map = std::move(*InstrumentationMapOrError);
383 const auto &FunctionAddresses = Map.getFunctionAddresses();
384 symbolize::LLVMSymbolizer::Options Opts(
385 symbolize::FunctionNameKind::LinkageName, true, true, false, "");
386 symbolize::LLVMSymbolizer Symbolizer(Opts);
387 llvm::xray::FuncIdConversionHelper FuncIdHelper(ConvertInstrMap, Symbolizer,
389 llvm::xray::TraceConverter TC(FuncIdHelper, ConvertSymbolize);
391 raw_fd_ostream OS(ConvertOutput, EC,
392 ConvertOutputFormat == ConvertFormats::BINARY
393 ? sys::fs::OpenFlags::F_None
394 : sys::fs::OpenFlags::F_Text);
396 return make_error<StringError>(
397 Twine("Cannot open file '") + ConvertOutput + "' for writing.", EC);
399 auto TraceOrErr = loadTraceFile(ConvertInput, ConvertSortInput);
402 make_error<StringError>(
403 Twine("Failed loading input file '") + ConvertInput + "'.",
404 std::make_error_code(std::errc::executable_format_error)),
405 TraceOrErr.takeError());
407 auto &T = *TraceOrErr;
408 switch (ConvertOutputFormat) {
409 case ConvertFormats::YAML:
410 TC.exportAsYAML(T, OS);
412 case ConvertFormats::BINARY:
413 TC.exportAsRAWv1(T, OS);
415 case ConvertFormats::CHROME_TRACE_EVENT:
416 TC.exportAsChromeTraceEventFormat(T, OS);
419 return Error::success();