[Interpreter] Add Ignition profile visualization tool.

A new script is introduced, linux_perf_report.py, which reads Linux perf
data collected when running with FLAG_perf_basic_prof enabled and
produces an input file for flamegraph.pl, or a report of the hottest
bytecode handlers.

The bottom blocks of the produced flamegraph are bytecode handlers.
Special bottom blocks exist as well for compile routines, time spent
outside the interpreter and interpreter entry trampolines.

Because various Stubs and other pieces of JITted code do not maintain the
frame pointer, some sampled callchains might be incomplete even if V8 is
compiled with no_omit_framepointer=on. The script is able to detect the
most common anomaly where an entry trampoline appears in a chain, but not
on top, meaning that the frame of another bytecode handler is hidden. In
this case, the sample will be moved to a [misattributed] group to avoid
skewing the profile of unrelated handlers.

Misattributed samples and compilation routines are hidden by default.

BUG=v8:4899
LOG=N

Review URL: https://codereview.chromium.org/1783503002

Cr-Commit-Position: refs/heads/master@{#35574}
This commit is contained in:
ssanfilippo 2016-04-18 04:46:22 -07:00 committed by Commit bot
parent baca9a9b75
commit 8b5d4c74ec
2 changed files with 369 additions and 0 deletions

View File

@ -0,0 +1,222 @@
#! /usr/bin/python2
#
# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
import argparse
import collections
import re
import subprocess
import sys
__DESCRIPTION = """
Processes a perf.data sample file and reports the hottest Ignition bytecodes,
or write an input file for flamegraph.pl.
"""
__HELP_EPILOGUE = """
examples:
# Get a flamegraph for Ignition bytecode handlers on Octane benchmark,
# without considering the time spent compiling JS code, entry trampoline
# samples and other non-Ignition samples.
#
$ tools/run-perf.sh out/x64.release/d8 \\
--ignition --noturbo --nocrankshaft run.js
$ tools/ignition/linux_perf_report.py --flamegraph -o out.collapsed
$ flamegraph.pl --colors js out.collapsed > out.svg
# Same as above, but show all samples, including time spent compiling JS code,
# entry trampoline samples and other samples.
$ # ...
$ tools/ignition/linux_perf_report.py \\
--flamegraph --show-all -o out.collapsed
$ # ...
# Same as above, but show full function signatures in the flamegraph.
$ # ...
$ tools/ignition/linux_perf_report.py \\
--flamegraph --show-full-signatures -o out.collapsed
$ # ...
# See the hottest bytecodes on Octane benchmark, by number of samples.
#
$ tools/run-perf.sh out/x64.release/d8 \\
--ignition --noturbo --nocrankshaft octane/run.js
$ tools/ignition/linux_perf_report.py
"""
COMPILER_SYMBOLS_RE = re.compile(
r"v8::internal::(?:\(anonymous namespace\)::)?Compile|v8::internal::Parser")
def strip_function_parameters(symbol):
if symbol[-1] != ')': return symbol
pos = 1
parenthesis_count = 0
for c in reversed(symbol):
if c == ')':
parenthesis_count += 1
elif c == '(':
parenthesis_count -= 1
if parenthesis_count == 0:
break
else:
pos += 1
return symbol[:-pos]
def collapsed_callchains_generator(perf_stream, show_all=False,
show_full_signatures=False):
current_chain = []
skip_until_end_of_chain = False
compiler_symbol_in_chain = False
for line in perf_stream:
# Lines starting with a "#" are comments, skip them.
if line[0] == "#":
continue
line = line.strip()
# Empty line signals the end of the callchain.
if not line:
if not skip_until_end_of_chain and current_chain and show_all:
current_chain.append("[other]")
yield current_chain
# Reset parser status.
current_chain = []
skip_until_end_of_chain = False
compiler_symbol_in_chain = False
continue
if skip_until_end_of_chain:
continue
symbol = line.split(" ", 1)[1]
if not show_full_signatures:
symbol = strip_function_parameters(symbol)
current_chain.append(symbol)
if symbol.startswith("BytecodeHandler:"):
yield current_chain
skip_until_end_of_chain = True
elif symbol == "Stub:CEntryStub" and compiler_symbol_in_chain:
if show_all:
current_chain[-1] = "[compiler]"
yield current_chain
skip_until_end_of_chain = True
elif COMPILER_SYMBOLS_RE.match(symbol):
compiler_symbol_in_chain = True
elif symbol == "Builtin:InterpreterEntryTrampoline":
if len(current_chain) == 1:
yield ["[entry trampoline]"]
elif show_all:
# If we see an InterpreterEntryTrampoline which is not at the top of the
# chain and doesn't have a BytecodeHandler above it, then we have
# skipped the top BytecodeHandler due to the top-level stub not building
# a frame. File the chain in the [misattributed] bucket.
current_chain[-1] = "[misattributed]"
yield current_chain
skip_until_end_of_chain = True
def calculate_samples_count_per_callchain(callchains):
chain_counters = collections.defaultdict(int)
for callchain in callchains:
key = ";".join(reversed(callchain))
chain_counters[key] += 1
return chain_counters.items()
def calculate_samples_count_per_handler(callchains):
def strip_handler_prefix_if_any(handler):
return handler if handler[0] == "[" else handler.split(":", 1)[1]
handler_counters = collections.defaultdict(int)
for callchain in callchains:
handler = strip_handler_prefix_if_any(callchain[-1])
handler_counters[handler] += 1
return handler_counters.items()
def write_flamegraph_input_file(output_stream, callchains):
for callchain, count in calculate_samples_count_per_callchain(callchains):
output_stream.write("{}; {}\n".format(callchain, count))
def write_handlers_report(output_stream, callchains):
handler_counters = calculate_samples_count_per_handler(callchains)
samples_num = sum(counter for _, counter in handler_counters)
# Sort by decreasing number of samples
handler_counters.sort(key=lambda entry: entry[1], reverse=True)
for bytecode_name, count in handler_counters:
output_stream.write(
"{}\t{}\t{:.3f}%\n".format(bytecode_name, count,
100. * count / samples_num))
def parse_command_line():
command_line_parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__DESCRIPTION,
epilog=__HELP_EPILOGUE)
command_line_parser.add_argument(
"perf_filename",
help="perf sample file to process (default: perf.data)",
nargs="?",
default="perf.data",
metavar="<perf filename>"
)
command_line_parser.add_argument(
"--flamegraph", "-f",
help="output an input file for flamegraph.pl, not a report",
action="store_true",
dest="output_flamegraph"
)
command_line_parser.add_argument(
"--show-all", "-a",
help="show samples outside Ignition bytecode handlers",
action="store_true"
)
command_line_parser.add_argument(
"--show-full-signatures", "-s",
help="show full signatures instead of function names",
action="store_true"
)
command_line_parser.add_argument(
"--output", "-o",
help="output file name (stdout if omitted)",
type=argparse.FileType('wt'),
default=sys.stdout,
metavar="<output filename>",
dest="output_stream"
)
return command_line_parser.parse_args()
def main():
program_options = parse_command_line()
perf = subprocess.Popen(["perf", "script", "-f", "ip,sym",
"-i", program_options.perf_filename],
stdout=subprocess.PIPE)
callchains = collapsed_callchains_generator(
perf.stdout, program_options.show_all,
program_options.show_full_signatures)
if program_options.output_flamegraph:
write_flamegraph_input_file(program_options.output_stream, callchains)
else:
write_handlers_report(program_options.output_stream, callchains)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,147 @@
# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import linux_perf_report as ipr
import StringIO
import unittest
PERF_SCRIPT_OUTPUT = """
# This line is a comment
# This should be ignored too
#
# cdefab01 aRandomSymbol::Name(to, be, ignored)
00000000 firstSymbol
00000123 secondSymbol
01234567 foo
abcdef76 BytecodeHandler:bar
76543210 baz
# Indentation shouldn't matter (neither should this line)
01234567 foo
abcdef76 BytecodeHandler:bar
76543210 baz
01234567 beep
abcdef76 BytecodeHandler:bar
76543210 baz
01234567 hello
abcdef76 v8::internal::Compiler
00000000 Stub:CEntryStub
76543210 world
11111111 BytecodeHandler:nope
00000000 Lost
11111111 Builtin:InterpreterEntryTrampoline
22222222 bar
11111111 Builtin:InterpreterEntryTrampoline
22222222 bar
"""
class LinuxPerfReportTest(unittest.TestCase):
def test_collapsed_callchains_generator(self):
perf_stream = StringIO.StringIO(PERF_SCRIPT_OUTPUT)
callchains = list(ipr.collapsed_callchains_generator(perf_stream))
self.assertListEqual(callchains, [
["foo", "BytecodeHandler:bar"],
["foo", "BytecodeHandler:bar"],
["beep", "BytecodeHandler:bar"],
["[entry trampoline]"],
])
def test_collapsed_callchains_generator_show_other(self):
perf_stream = StringIO.StringIO(PERF_SCRIPT_OUTPUT)
callchains = list(ipr.collapsed_callchains_generator(perf_stream,
show_all=True))
self.assertListEqual(callchains, [
['firstSymbol', 'secondSymbol', '[other]'],
["foo", "BytecodeHandler:bar"],
["foo", "BytecodeHandler:bar"],
["beep", "BytecodeHandler:bar"],
["hello", "v8::internal::Compiler", "[compiler]"],
["Lost", "[misattributed]"],
["[entry trampoline]"],
])
def test_calculate_samples_count_per_callchain(self):
counters = ipr.calculate_samples_count_per_callchain([
["foo", "BytecodeHandler:bar"],
["foo", "BytecodeHandler:bar"],
["beep", "BytecodeHandler:bar"],
["hello", "v8::internal::Compiler", "[compiler]"],
])
self.assertItemsEqual(counters, [
('BytecodeHandler:bar;foo', 2),
('BytecodeHandler:bar;beep', 1),
('[compiler];v8::internal::Compiler;hello', 1),
])
def test_calculate_samples_count_per_callchain(self):
counters = ipr.calculate_samples_count_per_callchain([
["foo", "BytecodeHandler:bar"],
["foo", "BytecodeHandler:bar"],
["beep", "BytecodeHandler:bar"],
])
self.assertItemsEqual(counters, [
('BytecodeHandler:bar;foo', 2),
('BytecodeHandler:bar;beep', 1),
])
def test_calculate_samples_count_per_handler_show_compile(self):
counters = ipr.calculate_samples_count_per_handler([
["foo", "BytecodeHandler:bar"],
["foo", "BytecodeHandler:bar"],
["beep", "BytecodeHandler:bar"],
["hello", "v8::internal::Compiler", "[compiler]"],
])
self.assertItemsEqual(counters, [
("bar", 3),
("[compiler]", 1)
])
def test_calculate_samples_count_per_handler_(self):
counters = ipr.calculate_samples_count_per_handler([
["foo", "BytecodeHandler:bar"],
["foo", "BytecodeHandler:bar"],
["beep", "BytecodeHandler:bar"],
])
self.assertItemsEqual(counters, [("bar", 3)])
def test_multiple_handlers(self):
perf_stream = StringIO.StringIO("""
0000 foo(bar)
1234 BytecodeHandler:first
5678 a::random::call<to>(something, else)
9abc BytecodeHandler:second
def0 otherIrrelevant(stuff)
1111 entrypoint
""")
callchains = list(ipr.collapsed_callchains_generator(perf_stream, False))
self.assertListEqual(callchains, [
["foo", "BytecodeHandler:first"],
])
def test_compiler_symbols_regex(self):
compiler_symbols = [
"v8::internal::Parser",
"v8::internal::(anonymous namespace)::Compile",
"v8::internal::Compiler::foo",
]
for compiler_symbol in compiler_symbols:
self.assertTrue(ipr.COMPILER_SYMBOLS_RE.match(compiler_symbol))
def test_strip_function_parameters(self):
def should_match(signature, name):
self.assertEqual(ipr.strip_function_parameters(signature), name)
should_match("foo(bar)", "foo"),
should_match("Foo(foomatic::(anonymous)::bar(baz))", "Foo"),
should_match("v8::(anonymous ns)::bar<thing(with, parentheses)>(baz, poe)",
"v8::(anonymous ns)::bar<thing(with, parentheses)>")