From: Ian Rogers <irogers@google.com>
To: Peter Zijlstra <peterz@infradead.org>,
Ingo Molnar <mingo@redhat.com>,
Arnaldo Carvalho de Melo <acme@kernel.org>,
Namhyung Kim <namhyung@kernel.org>, Jiri Olsa <jolsa@kernel.org>,
Adrian Hunter <adrian.hunter@intel.com>,
James Clark <james.clark@linaro.org>,
Mark Rutland <mark.rutland@arm.com>,
Alexander Shishkin <alexander.shishkin@linux.intel.com>
Cc: Dapeng Mi <dapeng1.mi@linux.intel.com>,
Zide Chen <zide.chen@intel.com>,
Thomas Falcon <thomas.falcon@intel.com>,
Chun-Tse Shao <ctshao@google.com>,
Lalit Maganti <lalitmaganti@gmail.com>,
linux-perf-users@vger.kernel.org, linux-kernel@vger.kernel.org,
Ian Rogers <irogers@google.com>,
Sandipan Das <sandipan.das@amd.com>
Subject: [PATCH 02/36] perf pmu-events: Fix Simplify() and Equals() bugs in metric.py
Date: Wed, 2 Dec 2026 00:20:53 -0800 [thread overview]
Message-ID: <62816a31f3392fc4c85583bde51adad7c18cb44a.1796199085.git.irogers@google.com> (raw)
In-Reply-To: <cover.1796199085.git.irogers@google.com>
Fix constant folding and equality bugs in metric.py:
- Operator.Simplify(): evaluate constant expressions using Decimal
matching perf's expr.y semantics instead of ast.literal_eval(), which
raises ValueError on *, /, %, <, >, &, |, and ^, and check
isinstance(lhs, Constant) on the simplified lhs rather than self.lhs.
- Function.Simplify(): add the missing return on d_ratio constant
folding and evaluate d_ratio/min/max directly instead of calling
ast.literal_eval().
- Function.Equals(): handle one-sided rhs is None instead of returning
True or raising AttributeError.
- Constant.__init__(): normalize -0 to 0.
Add unit tests covering these cases and aggr_nr() parsing.
Fixes: 40769665b63d ("perf jevents: Parse metrics during conversion")
Fixes: 3241cd11d9a0 ("perf jevents metric: Correct Function equality")
Signed-off-by: Ian Rogers <irogers@google.com>
---
tools/perf/pmu-events/metric.py | 50 ++++++++++++++++++++++------
tools/perf/pmu-events/metric_test.py | 40 ++++++++++++++++++++++
2 files changed, 80 insertions(+), 10 deletions(-)
diff --git a/tools/perf/pmu-events/metric.py b/tools/perf/pmu-events/metric.py
index f5d81eccd5c3..04bb29ce7722 100644
--- a/tools/perf/pmu-events/metric.py
+++ b/tools/perf/pmu-events/metric.py
@@ -273,9 +273,32 @@ class Operator(Expression):
lhs = self.lhs.Simplify()
rhs = self.rhs.Simplify()
if isinstance(lhs, Constant) and isinstance(rhs, Constant):
- return Constant(ast.literal_eval(lhs.value + self.operator + rhs.value))
-
- if isinstance(self.lhs, Constant):
+ l = decimal.Decimal(lhs.value)
+ r = decimal.Decimal(rhs.value)
+ if self.operator == '|':
+ return Constant(0 if l == 0 and r == 0 else 1)
+ if self.operator == '&':
+ return Constant(1 if l != 0 and r != 0 else 0)
+ if self.operator == '^':
+ return Constant(1 if (l == 0) != (r == 0) else 0)
+ if self.operator == '<':
+ return Constant(1 if l < r else 0)
+ if self.operator == '>':
+ return Constant(1 if l > r else 0)
+ if self.operator == '+':
+ return Constant(l + r)
+ if self.operator == '-':
+ return Constant(l - r)
+ if self.operator == '*':
+ return Constant(l * r)
+ if self.operator == '/' and r != 0:
+ return Constant(l / r)
+ if self.operator == '%' and int(r) != 0:
+ li, ri = int(l), int(r)
+ # Match C integer remainder (truncating toward zero) used by perf's expr.y.
+ return Constant(li - int(li / ri) * ri)
+
+ if isinstance(lhs, Constant):
if self.operator in ('+', '|') and lhs.value == '0':
return rhs
@@ -395,11 +418,16 @@ class Function(Expression):
lhs = self.lhs.Simplify()
rhs = self.rhs.Simplify() if self.rhs else None
if isinstance(lhs, Constant) and isinstance(rhs, Constant):
+ l = decimal.Decimal(lhs.value)
+ r = decimal.Decimal(rhs.value)
if self.fn == 'd_ratio':
- if rhs.value == '0':
+ if r == 0:
return Constant(0)
- Constant(ast.literal_eval(f'{lhs} / {rhs}'))
- return Constant(ast.literal_eval(f'{self.fn}({lhs}, {rhs})'))
+ return Constant(l / r)
+ if self.fn == 'min':
+ return lhs if l <= r else rhs
+ if self.fn == 'max':
+ return lhs if l >= r else rhs
return Function(self.fn, lhs, rhs)
@@ -410,9 +438,9 @@ class Function(Expression):
def Equals(self, other: Expression) -> bool:
if isinstance(other, Function):
result = self.fn == other.fn and self.lhs.Equals(other.lhs)
- if self.rhs:
- result = result and self.rhs.Equals(other.rhs)
- return result
+ if self.rhs is None or other.rhs is None:
+ return result and self.rhs is other.rhs
+ return result and self.rhs.Equals(other.rhs)
return False
def Substitute(self, name: str, expression: Expression) -> Expression:
@@ -494,10 +522,12 @@ class MetricRef(Expression):
class Constant(Expression):
"""A constant within the expression tree."""
- def __init__(self, value: Union[float, str]):
+ def __init__(self, value: Union[float, str, decimal.Decimal]):
ctx = decimal.Context()
ctx.prec = 20
dec = ctx.create_decimal(repr(value) if isinstance(value, float) else value)
+ if dec == 0:
+ dec = decimal.Decimal(0)
self.value = dec.normalize().to_eng_string()
self.value = self.value.replace('+', '')
self.value = self.value.replace('E', 'e')
diff --git a/tools/perf/pmu-events/metric_test.py b/tools/perf/pmu-events/metric_test.py
index 8acfe4652b55..0221ac746ec2 100755
--- a/tools/perf/pmu-events/metric_test.py
+++ b/tools/perf/pmu-events/metric_test.py
@@ -4,6 +4,7 @@ import unittest
from metric import Constant
from metric import Event
from metric import Expression
+from metric import Function
from metric import ParsePerfJson
from metric import RewriteMetricsInTermsOfOthers
@@ -65,6 +66,16 @@ class TestMetricExpressions(unittest.TestCase):
after = before
self.assertEqual(ParsePerfJson(before).ToPerfJson(), after)
+ def test_ParseAggrNr(self):
+ before = 'aggr_nr(UNC_CHA_CLOCKTICKS)'
+ self.assertEqual(ParsePerfJson(before).ToPerfJson(), before)
+
+ before = 'a / pcu_0@UNC_P_CLOCKTICKS@ * aggr_nr(pcu_0@UNC_P_CLOCKTICKS@)'
+ self.assertEqual(ParsePerfJson(before).ToPerfJson(), before)
+
+ before = 'a / (b / aggr_nr(c))'
+ self.assertEqual(ParsePerfJson(before).ToPerfJson(), before)
+
def test_IfElseTests(self):
# if-else needs rewriting to Select and back.
before = r'Event1 if #smt_on else Event2'
@@ -160,6 +171,35 @@ class TestMetricExpressions(unittest.TestCase):
after = '0 * SLOTS'
self.assertEqual(ParsePerfJson(before).Simplify().ToPerfJson(), after)
+ # Constant folding for non-add/sub operators and simplified lhs.
+ self.assertEqual((Constant(2) * Constant(3)).Simplify().ToPerfJson(), '6')
+ self.assertEqual((Constant(6) / Constant(4)).Simplify().ToPerfJson(), '1.5')
+ self.assertEqual((Constant(7) % Constant(4)).Simplify().ToPerfJson(), '3')
+ self.assertEqual((Constant(1) < Constant(2)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(1) > Constant(2)).Simplify().ToPerfJson(), '0')
+ self.assertEqual((Constant(2) & Constant(3)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(2) & Constant(0)).Simplify().ToPerfJson(), '0')
+ self.assertEqual((Constant(0) | Constant(5)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(2) ^ Constant(3)).Simplify().ToPerfJson(), '0')
+ self.assertEqual((Constant(2) ^ Constant(0)).Simplify().ToPerfJson(), '1')
+ self.assertEqual((Constant(1) / Constant(0)).Simplify().ToPerfJson(), '1 / 0')
+ self.assertEqual(ParsePerfJson('(0 if 1 else b) + a').Simplify().ToPerfJson(), 'a')
+ self.assertEqual(ParsePerfJson('(1 if 1 else b) * a').Simplify().ToPerfJson(), 'a')
+
+ # Constant folding in Function.Simplify().
+ self.assertEqual(ParsePerfJson('d_ratio(6, 4)').Simplify().ToPerfJson(), '1.5')
+ self.assertEqual(ParsePerfJson('d_ratio(6, 0)').Simplify().ToPerfJson(), '0')
+ self.assertEqual(ParsePerfJson('min(3, 5)').Simplify().ToPerfJson(), '3')
+ self.assertEqual(ParsePerfJson('max(3, 5)').Simplify().ToPerfJson(), '5')
+
+ def test_FunctionEquals(self):
+ f1 = Function('f', Event('a'))
+ f2 = Function('f', Event('a'), Event('b'))
+ self.assertFalse(f1.Equals(f2))
+ self.assertFalse(f2.Equals(f1))
+ self.assertTrue(f1.Equals(Function('f', Event('a'))))
+ self.assertTrue(f2.Equals(Function('f', Event('a'), Event('b'))))
+
def test_RewriteMetricsInTermsOfOthers(self):
Expression.__eq__ = lambda e1, e2: e1.Equals(e2)
before = [('cpu', 'm1', ParsePerfJson('a + b + c + d')),
--
2.56.1.915.g69d5ec7298-goog
next prev parent reply other threads:[~2026-12-02 8:21 UTC|newest]
Thread overview: 38+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-02 8:20 [PATCH 00/36] perf pmu-events: Intel event/metric fixes and TMA 5.32 updates Ian Rogers
2026-12-02 8:20 ` [PATCH 01/36] perf jevents: Map cpu_lowpower unit and handle uppercase 0X hex values Ian Rogers
2026-12-02 9:36 ` Mi, Dapeng
2026-12-02 8:20 ` Ian Rogers [this message]
2026-12-02 8:20 ` [PATCH 03/36] perf pmu-events: Remove 0 * slots simplification exception in metric.py Ian Rogers
2026-12-02 8:20 ` [PATCH 04/36] perf vendor events intel: Update alderlake events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:20 ` [PATCH 05/36] perf vendor events intel: Update alderlaken events and metrics Ian Rogers
2026-12-02 8:20 ` [PATCH 06/36] perf vendor events intel: Update arrowlake events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:20 ` [PATCH 07/36] perf vendor events intel: Update broadwell " Ian Rogers
2026-12-02 8:20 ` [PATCH 08/36] perf vendor events intel: Update broadwellde metrics to TMA 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 09/36] perf vendor events intel: Update broadwellx events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 10/36] perf vendor events intel: Update cascadelakex " Ian Rogers
2026-12-02 8:21 ` [PATCH 11/36] perf vendor events intel: Update clearwaterforest events and metrics Ian Rogers
2026-12-02 8:21 ` [PATCH 12/36] perf vendor events intel: Add diamondrapids TMA 5.32 metrics and update events Ian Rogers
2026-12-02 8:21 ` [PATCH 13/36] perf vendor events intel: Update elkhartlake events Ian Rogers
2026-12-02 8:21 ` [PATCH 14/36] perf vendor events intel: Update emeraldrapids events to 1.26 and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 15/36] perf vendor events intel: Update grandridge events and metrics Ian Rogers
2026-12-02 8:21 ` [PATCH 16/36] perf vendor events intel: Update graniterapids events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 17/36] perf vendor events intel: Update haswell " Ian Rogers
2026-12-02 8:21 ` [PATCH 18/36] perf vendor events intel: Update haswellx " Ian Rogers
2026-12-02 8:21 ` [PATCH 19/36] perf vendor events intel: Update icelake " Ian Rogers
2026-12-02 8:21 ` [PATCH 20/36] perf vendor events intel: Update icelakex " Ian Rogers
2026-12-02 8:21 ` [PATCH 21/36] perf vendor events intel: Update ivybridge metrics to TMA 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 22/36] perf vendor events intel: Update ivytown events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 23/36] perf vendor events intel: Update jaketown " Ian Rogers
2026-12-02 8:21 ` [PATCH 24/36] perf vendor events intel: Update knightslanding events Ian Rogers
2026-12-02 8:21 ` [PATCH 25/36] perf vendor events intel: Update lunarlake events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 26/36] perf vendor events intel: Update meteorlake " Ian Rogers
2026-12-02 8:21 ` [PATCH 27/36] perf vendor events intel: Update novalake events Ian Rogers
2026-12-02 8:21 ` [PATCH 28/36] perf vendor events intel: Update pantherlake events Ian Rogers
2026-12-02 8:21 ` [PATCH 29/36] perf vendor events intel: Update rocketlake events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 30/36] perf vendor events intel: Update sandybridge metrics to TMA 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 31/36] perf vendor events intel: Update sapphirerapids events to 1.41 and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 32/36] perf vendor events intel: Update sierraforest events and metrics Ian Rogers
2026-12-02 8:21 ` [PATCH 33/36] perf vendor events intel: Update skylake events and TMA metrics to 5.32 Ian Rogers
2026-12-02 8:21 ` [PATCH 34/36] perf vendor events intel: Update skylakex " Ian Rogers
2026-12-02 8:21 ` [PATCH 35/36] perf vendor events intel: Update snowridgex events Ian Rogers
2026-12-02 8:21 ` [PATCH 36/36] perf vendor events intel: Update tigerlake events and TMA metrics to 5.32 Ian Rogers
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=62816a31f3392fc4c85583bde51adad7c18cb44a.1796199085.git.irogers@google.com \
--to=irogers@google.com \
--cc=acme@kernel.org \
--cc=adrian.hunter@intel.com \
--cc=alexander.shishkin@linux.intel.com \
--cc=ctshao@google.com \
--cc=dapeng1.mi@linux.intel.com \
--cc=james.clark@linaro.org \
--cc=jolsa@kernel.org \
--cc=lalitmaganti@gmail.com \
--cc=linux-kernel@vger.kernel.org \
--cc=linux-perf-users@vger.kernel.org \
--cc=mark.rutland@arm.com \
--cc=mingo@redhat.com \
--cc=namhyung@kernel.org \
--cc=peterz@infradead.org \
--cc=sandipan.das@amd.com \
--cc=thomas.falcon@intel.com \
--cc=zide.chen@intel.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®